【问题标题】:Ruby and telnet: waitfor doesnt workRuby 和 telnet:waitfor 不起作用
【发布时间】:2013-06-07 11:14:34
【问题描述】:

我需要使用 Ruby 和 Telnet 登录服务器并执行一些命令。我的实际脚本是:

tn = Net::Telnet::new("Host" => "#{ip}", "Port"  => 23, "Timeout" => 60, 
     "Output_log"=>"output_log.log",
     "Dump_log"=> "dump_log.log",
     "Prompt" => /[#]/ )

tn.cmd("#{USER}\n#{PASS}") { |c| print c }

puts tn.cmd("Conf")
tn.waitfor(/config/) { |str| puts str }
puts tn.cmd("Int fa23")

puts tn.cmd("Shut")
puts tn.cmd("No shut")
puts tn.cmd("Exit")

tn.close

在输出中找到字符串“config”后,我必须只执行第二个命令 (Int fa23)。问题是 waitfor 不起作用。这是输出日志:

Trying XX.XX.XX.XX...
Connected to XX.XX.XX.XX.
User Name:username
Password:*************
BOT-SWT-VSAT-AL-...#Conf
BOT-SWT-VSAT-AL-...(config)#

脚本因等待超时错误而停止。我做错了什么?

【问题讨论】:

  • 这是一个非常有趣的脚本。我的问题是,我想,你的问题:你如何捕获输出?或者,也许您只需要处理日志...

标签: ruby timeout telnet


【解决方案1】:

请在 Net::Telnet::new 后面加上 waitfor

您应该等待连接建立(在创建 Telnet 实例时发生),然后等待服务器每次响应后再发送下一个命令。

        localhost = Net::Telnet::new("Host" => "*****",
                         "Port" => ***, 
                         "Timeout" => 10,
                         "Prompt" => /[$%#>] \z/n)
        localhost.waitfor(/USER/) {
           localhost.cmd("****") { 
              localhost.waitfor(/PASS/) {
                  |c| print c
                  # your next commands
                  ...
                  # localhost.close
              }
           }
        }

这里的关键是确保在响应之前您已收到来自服务器的所有数据包(直到收到 EOF)。然后有时,甚至消耗/等待空格字符也可能算在内(取决于您的 telnet 服务器的设计方式)。 然后,确保为匹配设置正确的正则表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2013-01-01
    相关资源
    最近更新 更多