Chapter 20. Extended Examples

Examples are an essential component in learning how to program. The explanations in this book are littered with examples. And while many are complete programs, most of them are small.

In contrast, this chapter is composed of several extended examples. Each is a complete Expect script drawing together many different concepts described in other chapters.

Encrypting A Directory

The UNIX crypt command encrypts a single file. Because it interactively prompts for a password, crypt is a pain to use if you want to encrypt a number of files all at the same time.

The cryptdir script, shown here, encrypts all the files in a directory. The current directory is used unless an argument is given, in which case that is used instead. If the script is called as decryptdir, the files are decrypted. Here is the beginning where the script figures out what it should do based on its name and arguments.

#!/usr/local/bin/expect —

# encrypt/decrypt an entire directory
# optional arg is dirname, else cwd

if {[llength $argv] > 0} {
    cd $argv

# encrypt or decrypt?
set decrypt [regexp "decrypt" $argv0]

Next, the script queries for a password. If the script is encrypting files, it asks for the password twice. This lowers the chance of encrypting files with an accidentally mistyped password.

set timeout −1
stty -echo
send "Password:"
expect -re "(.*)\n" send "\n" set passwd $expect_out(1,string) # wouldn't want to encrypt files with mistyped password! if !$decrypt { send "Again:" expect ...

Get Exploring Expect now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.