ruby telnet to windows 2008 ,execute command error

和自甴很熟 提交于 2019-12-13 04:58:58

问题


I tried to use ruby Net::Telnet to connect windows 2008 and execute some commands. But it failed.

if execute

tn = Net::Telnet::new("Host"=>"walnutserver","Port"=>2300,"Prompt"=> /C:.*>/)
tn.login("user","pass")
tn.cmd("dir")
tn.cmd("dir")

the first tn.cmd("dir") is success but the second one throws exceptions.And then subsequent commands all failed. After experimenting,I found that any windows command will cause this.

Exceptions:

Timeout::Error: timed out while waiting for more data
        from c:/troy/data/chef/chef-client11/chef/embedded/lib/ruby/1.9.1/net/telnet.rb:558:in `waitfor'
        from c:/troy/data/chef/chef-client11/chef/embedded/lib/ruby/1.9.1/net/telnet.rb:697:in `cmd'
        from (irb):20
        from c:/troy/data/chef/chef-client11/chef/embedded/bin/irb:12:in `<main>'

use sock.sysread() method to read responding, I found that terminal is blocked and display dir\r\n0x00More?

Buf if execute

tn = Net::Telnet::new("Host"=>"walnutserver","Port"=>2300,"Prompt"=> /C:.*>/)
tn.login("user","pass")
tn.cmd("ls")
tn.cmd("uname")

It't running normally. lsuname are some linux commands brought by chef which installed in target machine.

ruby version:ruby 1.9.3p286 (2012-10-12) [i386-mingw32]

I found someone else asking the same question on Stackoverflow, but he didn't get the solution. http://www.ruby-forum.com/topic/1516840

Need your help.


回答1:


solved. the reason is ruby net/telnet library use error newline seperator. Must be EOL(CR+LF) but CR+NULL . But I don't know who make the bug,windows or ruby? I write a monkey patch as below:

class Net::Telnet
    def print(string)
      string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]

      if @options["Binmode"]
        self.write(string)
      else
        if @telnet_option["BINARY"] and @telnet_option["SGA"]
          self.write(string.gsub(/\n/n, CR))
        elsif @telnet_option["SGA"]
          self.write(string.gsub(/\n/n, EOL)) ### fix here. reaplce CR+NULL bY EOL
        else
          self.write(string.gsub(/\n/n, EOL))
        end
      end
    end
end


来源:https://stackoverflow.com/questions/16410550/ruby-telnet-to-windows-2008-execute-command-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!