使用expect脚本多个ssh到cisco路由器

时间:2016-03-03 07:59:55

标签: bash ssh expect router cisco

我不是一个铁杆剧本的家伙,但是想要学习。我刚开始期待脚本在cisco路由器上自动执行任务。请温和地推动我朝着正确的方向前进。之后我会做相应的研究。

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

当前方法:我使用常规bash脚本调用此expect脚本。我可以使用两个expect脚本来实现该需求,但我想使用一个expect脚本来执行此操作。

实施例:     #设置变量     set router1 [lindex $ argv 0]     set router2 [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 "#"

1 个答案:

答案 0 :(得分: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 "#"