在cisco开关上运行命令

时间:2018-02-23 10:23:33

标签: bash shell unix cisco

我制作了以下脚本来登录交换机并执行命令。只要我执行脚本,它就会在不运行命令的情况下登录切换和退出。

#!/usr/bin/expect -f

set timeout 3000

spawn bash -c "ssh ananair@10.60.255.100"

expect "*assword:"

send "pass@123\n"

expect "*#"

send "show interfaces status"

2 个答案:

答案 0 :(得分:0)

我怀疑问题是您的最终\n中缺少send。如果您只是send "string",那么期望永远不会在命令的末尾点击Enter,并且由于没有最终expect,它会确定其工作已完成,并且退出,甚至可能在它之前有机会回应它发送但从未执行的命令。

请考虑以下事项:

#!/usr/bin/expect -f

set timeout 3000

spawn ssh switchhostname          # no need to run this inside a shell

expect "ssword:"

send "1ns3cur3\n"                 # it would be better to use key based auth...

expect "#"

send "term len 0\n"               # tell the switch to avoid "More" prompts

expect "#"

send "show interfaces status\n"   # note the final "\n"

expect "#"                        # don't quit until the "show" command finishes

您也可以考虑通过SNMP访问此信息。

答案 1 :(得分:0)

尝试\ r而不是\ n

我有我的期望脚本,我用它来登录我的cisco开关。然后我使用期望脚本中的交互,让我离开cisco提示符。

我需要修改它才能显示密码,但我绝对可以帮到你。

我不需要超时。

#!/usr/bin/expect
proc enable {} {
 expect "assword:" {
  send "<enable password>\r"
  expect "#" {
  }
 }
}

proc login {} {
 send "<login password>\r"
 expect {
  "failed" {
   send "<username>\r"
   enable
  }
  ">" {
   send "en\r"
   enable
  }
  "#" {
 }}
}
set user_computer_attached [lindex $argv 0]
set user_computer [split $user_computer_attached "@"]
spawn ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 \
-oGlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null \
-oStrictHostKeyChecking=no $user_computer_attached
expect_after eof {
  wait
  spawn telnet [lindex $user_computer 1]
  expect "name:"
  send [lindex $user_computer 0]
  send "\r"
  expect "assword:" {
   login
  }
}
expect "assword:" {
 login
}
interact