2015-06-09 76 views
0

这应该不是那么复杂,但似乎Ruby和Python Telnet库都有笨拙的API。任何人都可以告诉我如何向Telnet主机写入命令,然后将响应读入字符串进行一些处理?Telnet发送命令,然后读取响应

在我的情况下,使用换行符“SEND”将检索设备上的一些温度数据。

使用Python我想:

tn.write(b"SEND" + b"\r") 
str = tn.read_eager() 

返回什么。

在Ruby中我尝试:

tn.puts("SEND") 

应该返回的东西为好,我已经得到了工作的唯一的事情是:

tn.cmd("SEND") { |c| print c } 

,你不能做与c

我在这里错过了什么吗?我期待像Ruby中的Socket库,像一些代码:

s = TCPSocket.new 'localhost', 2000 

while line = s.gets # Read lines from socket 
    puts line   # and print them 
end 
+1

虽然你可以通过Telnet做的非常简陋的握手,你真的需要使用“预期”般的库为您提供反应意想不到的反应和/或长时间的延迟和超时的能力。有关Ruby“期望”建议,请参阅http://stackoverflow.com/q/7142978/128421。 –

+0

所以我看了一些python和ruby的期望库,看起来它们和telnet库有类似的设置。就我的应用程序而言,pexpect.expect()和telnetlib.wait_until()一样吗? – bischoffingston

+0

另一件事是我不想期待一个响应,我想将响应加载到一个变量中。对这些库的预期方法似乎只有在找到匹配的情况下才返回索引。 – bischoffingston

回答

0

我发现,如果你不提供块到cmd方法,它会给你回响应(假设远程登录不要求别的什么)。您可以一次发送所有命令(但将所有响应捆绑在一起)或执行多个调用,但是您必须执行嵌套块回调(否则我无法执行此操作)。

require 'net/telnet' 

class Client 
    # Fetch weather forecast for NYC. 
    # 
    # @return [String] 
    def response 
    fetch_all_in_one_response 
    # fetch_multiple_responses 
    ensure 
    disconnect 
    end 

    private 

    # Do all the commands at once and return everything on one go. 
    # 
    # @return [String] 
    def fetch_all_in_one_response 
    client.cmd("\nNYC\nX\n") 
    end 

    # Do multiple calls to retrieve the final forecast. 
    # 
    # @return [String] 
    def fetch_multiple_responses 
    client.cmd("\r") do 
     client.cmd("NYC\r") do 
     client.cmd("X\r") do |forecast| 
      return forecast 
     end 
     end 
    end 
    end 

    # Connect to remote server. 
    # 
    # @return [Net::Telnet] 
    def client 
    @client ||= Net::Telnet.new(
     'Host'  => 'rainmaker.wunderground.com', 
     'Timeout' => false, 
     'Output_log' => File.open('output.log', 'w') 
    ) 
    end 

    # Close connection to the remote server. 
    def disconnect 
    client.close 
    end 
end 

forecast = Client.new.response 
puts forecast