问题
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. ls
、uname
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