Expect implementation entirely in bash 

Newsgroups: comp.unix.shell,alt.comp.lang.shell.unix.bourne-bash,gnu.bash Date: 15 Oct 2005 18:53:22 -0700

A friend of mine was trying to drive a scripted telnet session using bash, and did not have tools like Perl, Tcl/Tk or expect available on the platform, so I wrote a bash function to implement "expect" functionality directly, taking advantage of bash's "/dev/tcp" feature. Below is the function, which expects the global "timeout" variable to be initialized, and expects file descriptor #3 to already be open for reading and writing.

After the function is a usage example that works with my CMC system (see http://gangplank.org/ for more information on the system) — since my server implements telnet and doesn't provide the login prompt until the telnet protocol initialization completes, I have it wait for a \377 byte that indicates the start of the telnet protocol sequence. A similar technique could be used to send a telnet protocol response string for a known initial protocol sequence.

Also straightforward would be using the 3-digit codes in a protocol such as SMTP with this function to send an email, or to implement other such protocols.

Deven

#!/bin/bash

timeout=600

expect() {
   local expect="$1" send="$2"
   local delim="${expect:(-1):1}"
   local buffer="" block=""
   while read -u3 -r -t$timeout -d "$delim" block; do
      buffer="$buffer$block$delim"
      case "$buffer" in
         *"$expect")
            echo "$send" 1>&3
            return
            ;;
      esac
   done
}

exec 3<>/dev/tcp/localhost/9999
expect "`echo -en '\377'`" "guest"
expect "name:" "testing"
expect "blurb:" "testing2"

Deven T. Corzine