December 2006
Intermediate to advanced
1188 pages
72h 8m
English
You want to automate the process of logging into a router, typing usernames, passwords, and so forth.
The following script automates the process of logging into the router using a scripting language called Expect. Expect is a powerful scripting language that provides automation of interactive sessions (see Appendix A for more details). The script takes a router name or IP address as a command line argument. It then performs an automated login sequence before returning the session back to you for a normal interactive session.
Here is the sample output:
Freebsd%telspawn telnet Router1 Trying 172.25.1.5... Connected to Router1. Escape character is '^]'. User Access Verification Username: ijbrown Password: Router1> Router1 - vty login ok enable Password: Router1# Router1 - enable login ok Router1#term mon Router1#Router1
The Expect code follows in Example 3-3.
Example 3-3. tel
#!/usr/local/bin/expect # # tel -- a script to perform automated login onto a Cisco # router using either a hostname or IP address. # # # Set behaviour set userid ijbrown set vtypasswd oreilly set enablepwd cookbook # # set timeout 10 set rtr [lindex $argv 0] spawn telnet $rtr expect { {Username} { send "$userid\r" expect { {*Password*} { send "$vtypasswd\r" } } } {telnet>} { send_user "$rtr - telnet failed\n" exit } {Password} { send "$vtypasswd\r" } } expect { {Password} { send_user "\n$rtr - vty login failed\n" exit } {Username} { send_user "\n$rtr - vty login failed\n" ...Read now
Unlock full access