Example—Anonymous ftp

The interact command is ideal for building a script I call aftp. This script consists of the user/password interaction from the previous example and an interact command. The complete aftp script is shown below.

Anytime you want to begin anonymous ftp, you can use this little script and it will automatically supply the appropriate identification and then turn control over to you. When you type quit to ftp, ftp will exit, so interact will exit, and then the script will exit.

#!/usr/local/bin/expect --
spawn ftp $argv
expect "Name"
send "anonymous\r"
expect "Password:"
send "don@libes.com\r"
interact

Notice that the script does not wait for "ftp>" before the interact command. You could add another expect command to do that, but it would be redundant. Since the interact waits for characters from the process as well as the keyboard simultaneously, when the "ftp>" finally does arrive, interact will then display it. Presumably, a user will wait for the prompt before typing anyway so there is no functional benefit to using an explicit expect.

With only a little more, this script can be jazzed up in lots of ways. For example, rather then embedding your name in the script, you can pull it out of the environment by using the expression $env(USER). The full command in the script would be:

send "$env(USER)@libes.com\r"

It is a little more difficult to make this script portable to any machine because there is no standard command to retrieve the domain name (presuming you are ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.