【问题标题】:multiple ssh to cisco routers using expect script使用期望脚本的多个 ssh 到 cisco 路由器
【发布时间】:2023-08-22 07:13:02
【问题描述】:

我不是一个铁杆脚本专家,但我正在努力学习。我刚开始使用期望脚本来自动执行 cisco 路由器上的任务。请温柔地推动我朝着正确的方向前进。此后我会进行相应的研究。

要求:向 2 个不同的 cisco 路由器生成 2 个 ssh 会话,并在单个期望脚本中对每个路由器运行独特的命令。

当前方法:我使用常规 bash 脚本调用此期望脚本。我可以使用两个期望脚本来实现要求,但我想使用一个期望脚本来做到这一点。

示例: # 设置变量 设置路由器1 [lindex $argv 0] 设置路由器2 [lindex $argv 1] 设置用户名 [lindex $argv 2] 设置密码 [lindex $argv 3]

spawn ssh -o StrictHostKeyChecking=no $username\@$router1

expect "*assword"
send "$enablepassword\n"
expect "#"
send "command on router1"
expect "#"

close

#i want to close this ssh session and spawn ssh process to router2


spawn ssh -o StrictHostKeyChecking=no $username\@$router2 
#i tried this     simply in the same script and it doesn't work,mostly      because #it is not correct 

expect "*assword"
send "$enablepassword\n"
expect "#"
send "command on router2"
expect "#"

【问题讨论】:

  • 您是否需要同时与两个路由器交互?或者,按顺序交互它们就足够了?
  • 按顺序与他们互动就足够了

标签: bash ssh expect router cisco


【解决方案1】:

我认为你应该使用 spawn_id 全局变量,它有助于与多个 ssh 或 telnet 会话进行交互。 您的代码应如下所示:

spawn ssh -o StrictHostKeyChecking=no $username\@$router1
set R1 $spawn_id
expect -i $R1 "*assword"
send -i $R1 "$enablepassword\n"
expect -i $R1 "#"
send -i $R1 "command on router1"
expect -i $R1 "#"
send -i $R11 "exit\r"


spawn ssh -o StrictHostKeyChecking=no $username\@$router2 
set R2 $spawn_id

expect -i $R2 "*assword"
send -i $R2 "$enablepassword\n"
expect -i $R2 "#"
send -i $R2 "command on router2"
expect "#"

【讨论】: