Click Here to buy the full 72-page PDF for only £4.99, $9.99 or €6.99,
or the Kindle eBook (UK here - more countries and details here)
or the Kindle eBook (UK here - more countries and details here)
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 commandSo 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.
E[delay] expected_text
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.
#!/bin/sh
# expect.sh | telnet > file1
host=127.0.0.1
port=23
file=file1
MAX_WAITS=5
echo open ${host} ${port}
while read l
do
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}
fi
res=1
i=0
while [ "${res}" -ne "0" ]
do
tail -1 "${file}" 2>/dev/null | grep "${expected}" > /dev/null
res=$?
sleep $i
i=`expr $i + 1`
if [ "${i}" -gt "${MAX_WAITS}" ]; then
echo "ERROR : Waiting for ${expected}" >> ${file}
exit 1
fi
done
else
echo ${l} |cut -d" " -f2-
fi
done < expect.txt
This is run as so:
$ expect.sh | telnet > file1This 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 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
declan login: steve
Password:
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
cal
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
logout
Click Here to buy the full 72-page PDF for only £4.99, $9.99 or €6.99,
or the Kindle eBook (UK here - more countries and details here)
or the Kindle eBook (UK here - more countries and details here)
Steve's Bourne / Bash shell scripting tutorial

