I have a problem. A pain in the ass in my day when I need to deploy code to testing racks. Here's the situation....
We have multiple testing racks in the building to test entertainment systems. We also have multiple web servers on those racks that are basically stand alone web boxes used to interact with the system. Let's say we have 4 racks with 3 terminals who each have to be loaded by hand. (don't ask me why man!). So when I need to update my code for the developers and testers to use I have to do this little process

telnet to rack's gateway box
from gateway box, telnet to the web terminal
ncftp back to the gateway box
retrieve my latest code tar file
exit ncftp
untar new code
place code in proper directory
exit

thats EACH terminal. As you can imagine that could take a while with 4 racks, 3 terminals each. Silly me didn't think it was possible to actually script multiple telnet sessions. E.G.: Telnet to box1, then from box1 telnet to box2. I was wrong. Using the [url]http://expect.nist.gov/[/url] "EXPECT" program that comes standard on most linux and mac systems (there's a windows version too) you can actually script this without blinking an eye. From what I've found this is the only real decent way of doing this, everything else is just a hack and doesn't work reliably.


#!/usr/bin/expect
#---------------- TELNET TO INITIAL BOX1 -------------------------#
spawn telnet 203.288.183.144

#LOGIN
expect -re "login"
send "myUser\r"
expect -re "Password:"
send "myPassword\r"
expect "*box1]$*"

# TELNET TO BOX2 FROM BOX1
send "telnet 172.17.0.33\r"
expect "/ #"

# you now have command over box2 to do whatever commands you wish!
send "ls\r"
send "exit\r"
expect -re "box1"
send "exit\r"


Basically...spawn telnet 203.288.183.144 means start a new telnet session at this IP address

Now I expect I'm going to get prompted for a login right off the bat
expect -re "login"

I use the -re flag which means use regular expressions. So somewhere in string the GUI is showing I expect the word "login"

So I get "login" now I was to send it my login ID
send "myUser\r"

I'm sending my login name "myUser\r" notice the \r which acts as a user hitting the RETURN key on the keyboard.

Now I expect after I enter my username it wants my password
expect -re "Password:"

So I send it my password
send "myPassword\r"

Now I'm logged in and I expect to have a command prompt on box1
expect "*box1]$*"

Now I'm on box1 and I want to telnet to box2 from box1
send "telnet 172.17.0.33\r"
expect "/ #"

and boom, I'm on the command line of the 2nd box in my script and I can execute anything I want just using send and expect.


Using this simple technique you can automate all your interactive tasks such as telnet, ftp, ssh, etc. It's a whole new world. I can take more vacation now. Hope this helps someone out there looking to script telnet sessions :)

Ready for More?

Follow Me @jimplush