Ronald Michael
Ronald Michael

Reputation: 3

multiple ssh to cisco routers using expect script

I am not a hardcore script guy,but trying to learn.I just started with expect scripts to automate tasks on cisco router.Please be gentle and nudge me in the right direction.I will do research accordingly thereafter.

Requirement: to spawn 2 ssh sessions to 2 different cisco routers and run unique commands on each of them in a single expect script.

Current Method : I call this expect script using a regular bash script.I can achieve the requirement using two expect scripts,But I want to do this using one expect script.

Example: # Set variables set router1 [lindex $argv 0] set router2 [lindex $argv 1] set username [lindex $argv 2] set password [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 "#"

Upvotes: 0

Views: 4036

Answers (1)

qwpo
qwpo

Reputation: 91

I think you should use spawn_id global variable, it helps to interact with multiple ssh or telnet sessions. Your code should look something like this:

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 "#"

Upvotes: 1

Related Questions