Automating Network Tasks With Expect

I just got an email about automating some configuration changes, so I figured I would just post about it and send the link.

Basically anything on a network device can be scripted out using Expect as long as it has SSH or Telnet access open to it. There are other ways,such as SNMP set, but I use expect.

Here is a really simple one that you just run from a Linux shell:
/usr/bin/expect
set timeout 10
set hostname “10.4.5.6″

set username “name”
set password “password”
set enablepassword “itsasecret”
spawn telnet $hostname

expect “Username:” {
send “$username\n”
expect “Password:”
send “$password\n”

expect “>” {
send “en\n”
expect “Password:”
send “$enablepassword\n”
expect “#” {
send “config t\n”
expect “#”
send “no tacacs-server host 10.4.11.2
no tacacs-server key 1 *******

tacacs-server host x.x.x.x
tacacs-server key ********

wr me
exit

}
}

interact
}

 

Here is a more automated one that uses the script and a list of IP addresses that you supply in a separate text file named “fw_IP.txt” (or whatever you like, just change it in the script on line 8 also):

 

 

#!/bin/sh
# argument for username
#echo $1
# argument for password
#echo $2
# argument for enable password
#echo $3
for i in $(cat fw_IP.txt); do
#echo $i
expect -c ‘
set timeout 15
spawn telnet ‘”$i”‘
expect -re “(sername:|ogin:)” { send “\’”$1″‘\r” }
expect -re “assword:” { send “\’”$2″‘\r” }
expect -re “(>|#)” { send “\enable\r” }
expect -re “assword:” { send “\’”$3″‘\r” }
expect -re “(fw1|fw2|fw3)(>|#)” { send “\show arp\r” }
expect -re “(>|#)” { send “\show run | in static\r” }
expect -re “(>|#)” { send “\exit\r” }

done

Tags:

Leave a Comment

You must be logged in to post a comment.