ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Internet & the Web

Script to login to multiple Cisco devices with Telnet & SSH using Expect

Updated on August 2, 2010

SSH login into multiple devices made easy!

You have a list of devices on SSH access that you want to login and execute a specific command, and your simple looped script is just not working because of the RSA fingerprint.

The authenticity of host 'xx.yy.zz.aa (xx.yy.zz.aa)' can't be established.
RSA key fingerprint is 7f:17:e5:b9:c2:99:10:ac:9c:8b:d5:5c:2e:4c:b4:d5.
Are you sure you want to continue connecting (yes/no)?

What do you do next?

Use the EXPECT!

EXPECT is a program that "talks" to other interactive programs according to a script.

EXPECT is a toolkit for automating interactive programs, such as TELNET, SSH and FTP. You can write and execute SSH or TELNET logon scripts and do whatever you wish using a script file from a Bastion host.

EXPECT reads commands from a script file, spawns a process like SSH or TELNET, sends text from the script file to the SSH process, saves every character returned from the SSH session, and “looks” for known character strings that the user “expected”. The script can test for different strings and execute different code based on the results.

Connecting to my switch manually
Connecting to my switch manually

#!/usr/bin/expect -f
#! /bin/bash

set force_conservative 0 ;# set to 1 to force conservative mode even if
;# script wasn't run conservatively originally
if {$force_conservative} {
set send_slow {1 .1}
proc send {ignore arg} {
sleep .1
exp_send -s -- $arg }
set timeout 3000
log_user 1
set var1 [lindex $argv 0 ]
set var2 [lindex $argv 1]
puts $var1
puts $var2
spawn telnet $var1
expect "Username: "
send -- "KrisPrem\r"
expect "*assword: "
send -- "mypassword\r"
log_user 1
expect "*>"
send "en\r"
expect "*assword: "
send -- "myenablepassword\r"

expect "$var2"
send-- "show clock\r"

send -- "exit\r"


automatically logged in and executed a command
automatically logged in and executed a command

In the script above, i've used variable var1 to save the IP address and variable var2 for special purpose.

In a router running IOS, when you are in global configuration mode you know the prompt would be # so, basically you could expect it to be # and use expect "# " in the script followed by send appropriate commands you wish to.

Hope this hub was helpful.


What's Next


I'm not so good at explaining thing. If you need more details on the above script let me know....

Anyway, I'll create a hubpage on automation for Cisco routers and Switches based on expect and nmap.


    0 of 8192 characters used
    Post Comment

    No comments yet.