0

我尝试使用 ruby​​ Net::Telnet 连接 windows 2008 并执行一些命令。但它失败了。

如果执行

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

第一个tn.cmd("dir")是成功,但第二个抛出异常。然后后续命令都失败了。经过实验,我发现任何windows命令都会导致这种情况。

例外:

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>'

使用 sock.sysread() 方法读取响应,我发现终端被阻塞并显示dir\r\n0x00More?

如果执行

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

它运行不正常ls、<code>uname是安装在目标机器上的chef带来的一些linux命令。

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

我发现有人在 Stackoverflow 上问同样的问题,但他没有得到解决方案。http://www.ruby-forum.com/topic/1516840

需要你的帮助。

4

1 回答 1

0

解决了。原因是 ruby​​ net/telnet 库使用错误换行符。必须是 EOL(CR+LF) 但 CR+NULL 。但我不知道是谁制造了这个 bug,windows 还是 ruby​​?我写了一个猴子补丁如下:

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
于 2013-05-08T08:15:35.143 回答