【问题标题】:Ruby script to telnet switchruby 脚本到 telnet 切换
【发布时间】:2012-05-25 20:51:06
【问题描述】:

我创建了以下 ruby​​ 脚本,它可以远程登录 Cisco 设备、远程登录 Cisco 设备并运行命令“show int status err”。

require 'net/telnet'

C3550_20_PterraEst = "192.168.244.20" #Enter the IP address here

USER = "user" #Enter username here

PASS = "password" #Enter password here

ENABLE = "password" #Enter enable password here

print "Selezionare il piano [0-1-2-All]: ";

# get the input from the console, 
val1 = gets;
tn = Net::Telnet::new("Host" => C3550_20_PterraEst,
"Timeout" => 5,
"Prompt" => /Username/ )
tn.cmd("\n#{USER}") 
tn.cmd(PASS) 
tn.cmd("sh int status err\n") { |c| print c }
exit

现在我希望那些 Cisco 设备输出(当我发送“show int status err”时)应该分配给我脚本中的一个变量...我解释得更好:

假设命令“show int status err”返回这个值:

int fa0/20 int fa0/25

我想做一些事情,例如... variable1 = 'Int fa0/20,Int fa0/25' 然后在我的脚本中使用 variable1。

我可以用女巫的方式吗?

【问题讨论】:

    标签: ruby telnet cisco


    【解决方案1】:

    我认为你想做的不是:

    tn.cmd("sh int status err\n") { |c| print c }
    

    而是:

    response = tn.cmd("sh int status err\n")
    

    根据 NET::Telnet 上的文档,Telnet#cmd 返回响应。如果你将它传递给一个块,它也会产生对该块的响应,但是如果你想将响应存储在一个变量中,我的示例是最好的方法。

    如果您还想打印对 STD 的响应,您应该能够同时执行这两项操作,如下所示:

    response = tn.cmd("sh int status err\n") { |c| print c }
    

    但是,如果 tn.cmd("sh int status err\n") { |c| print c } 给你一个错误,我的解决方案可能无法正常工作,直到你弄清楚它为什么会产生错误。如果您需要帮助解决该问题,您应该将其添加到 cmets。

    综上所述,如果您希望脚本生成其他命令以响应 telnet 响应,您可能需要考虑使用 [expect][1]。

    【讨论】:

      【解决方案2】:

      在这一行tn.cmd("sh int status err\n") { |c| print c } c 是命令的返回值,但由于它是一个局部变量,它存在于该块中。你可以使用instance variable 来包含它,这样你就可以在块外使用它。

      【讨论】:

      • 好的,但如果我执行以下操作:tn.cmd("sh int status err\n") { |@c| print @c } 它给了我错误;
      猜你喜欢
      • 2010-11-01
      • 2018-02-15
      • 2023-03-21
      • 1970-01-01
      • 2016-12-19
      • 2018-04-30
      • 2012-06-25
      • 1970-01-01
      • 2021-07-31
      相关资源
      最近更新 更多