Cisco Configuration “Expect” Backup Script

I was recently tasked with backing up switch configurations automatically. No problem, right? Wrong. There was nothing to spend on this project so it was up to me and whatever I could do with a script. I had made a telnet script in the past but was not crazy about passwords flying around in plain text. I really have very little scripting experience so many of you will find this very easy to understand and follow since there is nothing complicated about my scripting skills.

I used a Linux based system and the “expect” scripting language. Expect is great for automating tasks that are typically interactive. I could have used PERL or PHP (I am a bit more familiar with them) but apparently their SSH libraries don’t always play well with Cisco SSH servers. At any rate the expect script was easy enough and I set it up to take arguments that would be fairly interfaceable anyhow. The only pre requisite is to install “expect” on your system. Check the script out below:

#!/usr/bin/expect
#http://technologyordie.com/cisco-configuration-backup-script
set timeout 15
set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set tftp [lindex $argv 3]
set file [lindex $argv 4]
 
#Open the SSH session
spawn ssh -l $username $host
sleep 2
 
#Catch the password prompt and send supplied password
expect {
"word:" {send "$password\r"}
}
sleep 1
 
#Catch the enabled prompt and issue the command to backup configuration
expect {
"#" {send "copy startup-config tftp:\r"}
}
sleep 1
 
#Expect the two confirmation questions and answer
expect {
"?" {send "$tftp\r"}
}
sleep 1
expect {
"?" {send "$file\r"}
}
 
#Wait long enough for file transfer and exit
sleep 10

To use the script simpley follow this convention:

# ./script.exp  device username password tftp_server backup_filename

If you would like to learn more about Expect I suggest the book “Exploring Expect”
to get you familiar with the basics as well as some advanced Expect features.

I hope someone else finds this adaptable to their needs! As always, feel free to comment, and post changes or enhancements!

Download Script HERE

This entry was posted in Networking, Scripts, Shell and tagged , , , , , . Bookmark the permalink.

3 Responses to Cisco Configuration “Expect” Backup Script

    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.