【问题标题】:Telnet send command and then read responseTelnet 发送命令然后读取响应
【发布时间】:2015-08-24 21:41:49
【问题描述】:

这不应该那么复杂,但似乎 Ruby 和 Python Telnet 库都有笨拙的 API。谁能告诉我如何向 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

【问题讨论】:

  • 虽然您可以通过 Telnet 进行非常基本的握手,但您确实需要使用类似“expect”的库来为您提供对意外响应和/或长时间延迟和超时做出反应的能力。请参阅stackoverflow.com/q/7142978/128421 以获取 Ruby“预期”建议。
  • 所以我查看了一些用于 python 和 ruby​​ 的期望库,似乎它们具有与 telnet 库类似的设置。就我的应用程序而言,pexpect.expect() 是否与 telnetlib.wait_until() 相同?
  • 另一件事是我不想期待响应,我想将响应加载到变量中。如果找到匹配项,这些库上的 expect 方法似乎只返回一个索引。
  • 期望库允许您捕获结果。他们必须为了对您连接到的主机的响应进行子字符串和正则表达式匹配,然后才能匹配 CLI 提示等。

标签: python ruby telnet telnetlib


【解决方案1】:

我发现如果您不向 cmd 方法提供块,它会返回响应(假设 telnet 没有要求您提供任何其他内容)。您可以一次发送所有命令(但将所有响应捆绑在一起)或进行多次调用,但您必须进行嵌套块回调(否则我无法做到)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2013-04-09
    • 2014-01-30
    • 2018-12-13
    • 2017-04-13
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多