Script to login to multiple Cisco devices with Telnet & SSH using Expect
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.
#!/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"
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.
Automate your Cisco Configuration backup
- What needs to be backed-up from a Cisco Router
I worked with a senior Cisco HTTS engineer to churn out the set of most important commands that will give all possible data in Cisco box. Some of the command might not be supported in low end versions... - Automate the config backup of your Cisco routers and switches
It's always better to backup the configurations of your routers because, configuration of Routers/Switches often gets modified, a line or more is either added or deleted and sometimes router/switch itself are...