RSS Feed Share on Twitter

Buy this Shell Scripting Tutorial as a PDF for only $5

Simple Expect Replacement

Here is a simple replacement for expect. A number of people have asked how this is done, and inspired by Sun's example I showed in Hints and Tips which is used in Sun Microsystems' Explorer utility, here is a very simple version of expect.

The syntax of expect.txt is very simple:

S command
E[delay] expected_text
So a command is marked by starting with "S" (for Send), and the expected result is marked with "E". Since some commands can take a while to complete, it is possible to specify a delay before expecting the result: "E10 $" will wait for 10 seconds before expecting a dollar prompt.
If the expected text is not found, the script will wait one second, try again, then wait two seconds, then three seconds, until either the expected text is found, or it hits a maximum - as defined by MAX_WAITS. The delay is optional, so "E $" will expect a prompt immediately.

Note that if MAX_WAITS=5, the maximum delay will not be five, but 1+2+3+4+5=fifteen seconds.

# | telnet > file1 

echo open ${host} ${port}

while read l
  c=`echo ${l}|cut -c1`
  if [ "${c}" = "E" ]; then
    expected=`echo ${l}|cut -d" " -f2-`
    delay=`echo ${l}|cut -d" " -f1|cut -c2-`
    if [ -z "${delay}" ]; then
      sleep ${delay}
    while [ "${res}" -ne "0" ]
      tail -1 "${file}" 2>/dev/null | grep "${expected}" > /dev/null
      sleep $i
      i=`expr $i + 1`
      if [ "${i}" -gt "${MAX_WAITS}" ]; then
	echo "ERROR : Waiting for ${expected}" >> ${file}
	exit 1
    echo ${l} |cut -d" " -f2-
done < expect.txt
This is run as so:
$ | telnet > file1
This will create a file, file1, which contains a transcript of the session. In this case, that will be the login process, an ls of /tmp, and the output of cal. For example:
telnet> Trying
Connected to
Escape character is '^]'.

declan login: steve
Last login: Thu May 30 23:52:50 +0100 2002 on pts/3 from localhost.
No mail.
steve:~$ ls /tmp
API.txt		      cgihtml-1.69.tar.gz      orbit-root
a.txt		      cmd.txt		       orbit-steve
apache_1.3.23.tar.gz  defaults.cgi	       parser.c
b.txt		      diary.c		       patchdiag.xref
background.jpg	      drops.jpg		       sh-thd-1013541438
blocks.jpg	      fortune-mod-9708.tar.gz  stone-dark.jpg
blue3.jpg	      grey2.jpg		       water.jpg
c.txt		      jpsock.131.1249
steve:~$ cal
      May 2002
Su Mo Tu We Th Fr Sa 
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

steve:~$ exit



Books and eBooks


You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the end of the form, to prove that you are a real person!

You can buy the content of this Shell Scripting Tutorial as a PDF!