Expect scripts for automatic login with telnet and SSH
To speed up my everyday job of administering and maintaining network devices, I wrote two Expect scripts that enable me to automatically login to network devices with telnet or SSH. Both scripts have been thoroughly used and tested only with Cisco routers and switches. I call them my “autologin” scripts and they enabled me to also be much quicker when I need to troubleshoot problems in the network.
After you successfully login to a network device using its IP address, the script automatically saves all of the current and future session log for that device in a separate file with filename “session_$IPaddress.log” using the following structure:
### /START-TELNET/SSH-SESSION/ IP: $IPaddress @ [exec date] ###\r SESSION_LOG \r### /END-TELNET/SSH-SESSION/ IP: $IPaddress @ [exec date] ###\r
Script for automatic login with telnet:
#!/usr/bin/expect -f
set timeout 20
set IPaddress [lindex $argv 0]
set Username "your_username"
set Password "your_password"
set Directory DIRECTORY_PATH
log_file -a $Directory/session_$IPaddress.log
send_log "### /START-TELNET-SESSION/ IP: $IPaddress @ [exec date] ###\r"
spawn telnet $IPaddress
expect "Username: "
send "$Username\r"
expect "Password: "
send "$Password\r"
interact
send_log "\r### /END-TELNET-SESSION/ IP: $IPaddress @ [exec date] ###\r"
exit
Script for automatic login with SSH (with host key checking disabled):
#!/usr/bin/expect -f set timeout 20 set IPaddress [lindex $argv 0] set Username "your_username" set Password "your_password" set Directory DIRECTORY_PATH log_file -a $Directory/session_$IPaddress.log send_log "### /START-SSH-SESSION/ IP: $IPaddress @ [exec date] ###\r" spawn ssh -o "StrictHostKeyChecking no" $Username@$IPaddress expect "*assword: " send "$Password\r" interact send_log "\r### /END-SSH-SESSION/ IP: $IPaddress @ [exec date] ###\r" exit
To use the scripts you must save them in separate files (e.g. autotelnet.sh and autossh.sh), enter your username, password and DIRECTORY_PATH for saving session logs, make both scripts executable and add them to your system path so you can call them from the terminal line like this:
autotelnet [network_device_IP_address]
autossh [network_device_IP_address]
Hope it will be useful to someone.
Very important notice: If you decide to use the scripts, I don’t guaranty anything, so be careful and use them at your own risk.
Posted on August 15, 2010, in Network tools and tagged expect script, ssh, telnet. Bookmark the permalink. Leave a comment.




Leave a comment
Comments 0