Using expect with Cisco IOS

Following up my JunOS post, here is a handy script I cooked up to pull the configuration from a Cisco IOS device.  The one trip up for this stuff is sometimes you can logon to a cisco device, and you can be at the enabled state, you may have to enable,  and depending on how it’s configured you may have to use an enable password, which may be your password (again) or you may have to use a different password.

So yeah with a bunch of testing around this seems to work well enough for me.

#!/usr/local/bin/expect —
set MYUSER “my_user_name”
set MYPASS “my_password”
set ENPASS “my_enable_password”

set HOST [lindex $argv 0];
set timeout 90
if {$argc!=1} {
puts “Usage is scritpname <ip address>\r”
exit 1
}

#
#
puts “Connecting to $HOST\r”

spawn ssh $HOST -l $MYUSER

# Deal with hosts we’ve never talked to before
# or just logon
#
expect {
“*yes/no*” {send “yes\r” ; exp_continue }
“*assword:” {send “${MYPASS}\r” }
}
set ALREADY 0
expect {
“\r*>” {}
“\r*#” { set ALREADY 1}
“*enied” {exit 1}
“*assword” {exit 1}
}

if { $ALREADY < 1 } {

send “enable\r”
expect “*assword:” {
send “${MYPASS}\r”
expect {
“*enied” {
send “enable\r”
expect “*assword:”
send “${ENPASS}\r”
expect {
“*enied” {
exit 1}
“\r*#” {}
}
}
“\r*#” {}
}
}
}

send “show run\r”

expect {
“ore” {send ” “; exp_continue}
“\r*#” {}
}

#Let’s get out of here
send “q\r”
expect eof
exit 0

 

This is a little more cleaner than the prior JunOS one, as I’ll keep on improving it.

It works with ASA’s (tested 8.2)and IOS (tested 12.2)

2 thoughts on “Using expect with Cisco IOS

  1. Rather than feed the ‘more’ prompt, you can first entry ‘terminal length 0’ which will turn off the automore facility. If you want to be really clever, you could parse the output from ‘show terminal’ first, save the current length, and restore it at the end.

    • Ive usually found I had to make a change to the line # on the device, which I’d much rather not make any changes, and be as generic as possible.

      some of us old people like 24lines, and hate it when kids set the length to 0 when there is a 200kb config.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.