scripting an interactive telnet session

Something that always perplexed me was how to script sending an email. As we all know, telnet sessions are interactive, and there’s not much interactivity in a shell script that runs unattended. Turns out that things like this CAN be scripted after all, and in this example I’ll show you how to script a telnet session to an exchange server. Make sure this is one continuous line in your terminal window.

(sleep 1; echo "helo <exchange server>"; sleep 1; echo "mail from: $DRIVENAME"; sleep 1; echo "rcpt to: "; sleep 1; echo "data"; sleep 1; echo "Subject: $DRIVENAME finishing imaging on $DATE at $TIME"; sleep 1; echo "Ready for data transfer and roll-down."; sleep 1; echo "."; sleep 1; echo "quit") | telnet <exchange server> 25

The above code simulates an interactive session by piping echo commands. Since a pipe takes the output of the first command and uses it as input to the second command, we can script the interactive parts of a telnet session to an exchange server, lump it into a “single” command with the parentheses, and then pipe it to a telnet command. It helps to read this code segment almost backwards: First a telnet session is opened to port 25 on the exchange server. Then the program sleeps for 1 second to wait for the server to respond to the telnet, then it “enters” a helo by echoing it, waits for a response, and so forth. The ‘;’ separates multiple commands on a single line so the shell interpreter doesn’t go crazy.

I’ve been using this method for 2 years to alert the deploy teams in my company when a mac has finished imaging, so no one has to sit and watch them. The script I use searches for a particular process, and while found, sleeps for 60 seconds until it searches again. Once it no longer find the process, it exits the loop, sets a couple variables, and shoots off an email. You can view it here: http://dl.dropbox.com/u/5413877/mailStatus.sh


About this entry