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
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
My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.
![]() Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and in paperback format good to keep by your desk as an ever-present companion. Also available in PDF form from Gumroad:Get this tutorial as a PDF | ![]() Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half covers all of the features of the shell in every detail; the second half has real-world shell scripts, organised by topic, along with detailed discussion of each script. |