table of contents
EXPECT(1) | General Commands Manual | EXPECT(1) |
NAME¶
expect - programmed dialogue with interactive programs, Version 5SYNOPSIS¶
expect [ -dDinN ] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ]INTRODUCTION¶
Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue. In addition, the user can take control and interact directly when desired, afterward returning control to the script. Expectk is a mixture of Expect and Tk. It behaves just like Expect and Tk's wish. Expect can also be used directly in C or C++ (that is, without Tcl). See libexpect(3). The name "Expect" comes from the idea of send/expect sequences popularized by uucp, kermit and other modem control programs. However unlike uucp, Expect is generalized so that it can be run as a user-level command with any program and task in mind. Expect can actually talk to several programs at the same time. For example, here are some things Expect can do:- •
- Cause your computer to dial you back, so that you can login without paying for the call.
- •
- Start a game (e.g., rogue) and if the optimal configuration doesn't appear, restart it (again and again) until it does, then hand over control to you.
- •
- Run fsck, and in response to its questions, answer "yes", "no" or give control back to you, based on predetermined criteria.
- •
- Connect to another network or BBS (e.g., MCI Mail, CompuServe) and automatically retrieve your mail so that it appears as if it was originally sent to your local system.
- •
- Carry environment variables, current directory, or any kind of information across rlogin, telnet, tip, su, chgrp, etc.
USAGE¶
Expect reads cmdfile for a list of commands to execute. Expect may also be invoked implicitly on systems which support the #! notation by marking the script executable, and making the first line in your script:#!/usr/bin/expect -f
#!/usr/bin/expect --
send_user "$argv0 [lrange $argv 0 2]\n"
COMMANDS¶
Expect uses Tcl (Tool Command Language). Tcl provides control flow (e.g., if, for, break), expression evaluation and several other features such as recursion, procedure definition, etc. Commands used here but not defined (e.g., set, if, exec) are Tcl commands (see tcl(3)). Expect supports additional commands, described below. Unless otherwise specified, commands return the empty string. Commands are listed alphabetically so that they can be quickly located. However, new users may find it easier to start by reading the descriptions of spawn, send, expect, and interact, in that order.- close [-slave] [-onexec 0|1] [-i spawn_id]
- closes the connection to the current process. Most
interactive programs will detect EOF on their stdin and exit; thus
close usually suffices to kill the process as well. The -i
flag declares the process to close corresponding to the named spawn_id.
- debug [[-now] 0|1]
- controls a Tcl debugger allowing you to step through
statements, set breakpoints, etc.
- disconnect
- disconnects a forked process from the terminal. It continues running in the background. The process is given its own process group (if possible). Standard I/O is redirected to /dev/null.
- The following fragment uses disconnect to continue
running the script in the background.
if {[fork]!=0} exit disconnect . . .
The following script reads a password, and then runs a program every hour that demands a password each time it is run. The script supplies the password so that you only have to type it once. (See the stty command which demonstrates how to turn off password echoing.)send_user "password?\ " expect_user -re "(.*)\n" for {} 1 {} { if {[fork]!=0} {sleep 3600;continue} disconnect spawn priv_prog expect Password: send "$expect_out(1,string)\r" . . . exit }
An advantage to using disconnect over the shell asynchronous process feature (&) is that Expect can save the terminal parameters prior to disconnection, and then later apply them to new ptys. With &, Expect does not have a chance to read the terminal's parameters since the terminal is already disconnected by the time Expect receives control.
- exit [-opts] [status]
- causes Expect to exit or otherwise prepare to do so.
- exp_continue [-continue_timer]
- The command exp_continue allows expect itself to continue executing rather than returning as it normally would. By default exp_continue resets the timeout timer. The -continue_timer flag prevents timer from being restarted. (See expect for more information.)
- exp_internal [-f file] value
- causes further commands to send diagnostic information internal to Expect to stderr if value is non-zero. This output is disabled if value is 0. The diagnostic information includes every character received, and every attempt made to match the current output against the patterns.
- If the optional file is supplied, all normal and
debugging output is written to that file (regardless of the value of
value). Any previous diagnostic output file is closed.
- exp_open [args] [-i spawn_id]
- returns a Tcl file identifier that corresponds to the
original spawn id. The file identifier can then be used as if it were
opened by Tcl's open command. (The spawn id should no longer be
used. A wait should not be executed.
- exp_pid [-i spawn_id]
- returns the process id corresponding to the currently spawned process. If the -i flag is used, the pid returned corresponds to that of the given spawn id.
- exp_send
- is an alias for send.
- exp_send_error
- is an alias for send_error.
- exp_send_log
- is an alias for send_log.
- exp_send_tty
- is an alias for send_tty.
- exp_send_user
- is an alias for send_user.
- exp_version [[-exit] version]
- is useful for assuring that the script is compatible with the current version of Expect.
- With no arguments, the current version of Expect is returned. This version may then be encoded in your script. If you actually know that you are not using features of recent versions, you can specify an earlier version.
- Versions consist of three numbers separated by dots. First is the major number. Scripts written for versions of Expect with a different major number will almost certainly not work. exp_version returns an error if the major numbers do not match.
- Second is the minor number. Scripts written for a version with a greater minor number than the current version may depend upon some new feature and might not run. exp_version returns an error if the major numbers match, but the script minor number is greater than that of the running Expect.
- Third is a number that plays no part in the version comparison. However, it is incremented when the Expect software distribution is changed in any way, such as by additional documentation or optimization. It is reset to 0 upon each new minor version.
- With the -exit flag, Expect prints an error and exits if the version is out of date.
- expect [[-opts] pat1 body1] ... [-opts] patn [bodyn]
- waits until one of the patterns matches the output of a spawned process, a specified time period has passed, or an end-of-file is seen. If the final body is empty, it may be omitted.
- Patterns from the most recent expect_before command are implicitly used before any other patterns. Patterns from the most recent expect_after command are implicitly used after any other patterns.
- If the arguments to the entire expect statement require more than one line, all the arguments may be "braced" into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces.
- If a pattern is the keyword eof, the corresponding body is executed upon end-of-file. If a pattern is the keyword timeout, the corresponding body is executed upon timeout. If no timeout keyword is used, an implicit null action is executed upon timeout. The default timeout period is 10 seconds but may be set, for example to 30, by the command "set timeout 30". An infinite timeout may be designated by the value -1. If a pattern is the keyword default, the corresponding body is executed upon either timeout or end-of-file.
- If a pattern matches, then the corresponding body is executed. expect returns the result of the body (or the empty string if no pattern matched). In the event that multiple patterns match, the one appearing first is used to select a body.
- Each time new output arrives, it is compared to each pattern in the order they are listed. Thus, you may test for absence of a match by making the last pattern something guaranteed to appear, such as a prompt. In situations where there is no prompt, you must use timeout (just like you would if you were interacting manually).
- Patterns are specified in three ways. By default, patterns
are specified as with Tcl's string match command. (Such patterns
are also similar to C-shell regular expressions usually referred to as
"glob" patterns). The -gl flag may may be used to protect
patterns that might otherwise match expect flags from doing so. Any
pattern beginning with a "-" should be protected this way. (All
strings starting with "-" are reserved for future options.)
- For example, the following fragment looks for a successful
login. (Note that abort is presumed to be a procedure defined
elsewhere in the script.)
expect { busy {puts busy\n ; exp_continue} failed abort "invalid password" abort timeout abort connected }
Quotes are necessary on the fourth pattern since it contains a space, which would otherwise separate the pattern from the action. Patterns with the same action (such as the 3rd and 4th) require listing the actions again. This can be avoid by using regexp-style patterns (see below). More information on forming glob-style patterns can be found in the Tcl manual.
- Regexp-style patterns follow the syntax defined by Tcl's
regexp (short for "regular expression") command. regexp
patterns are introduced with the flag -re. The previous example can
be rewritten using a regexp as:
expect { busy {puts busy\n ; exp_continue} -re "failed|invalid password" abort timeout abort connected }
Both types of patterns are "unanchored". This means that patterns do not have to match the entire string, but can begin and end the match anywhere in the string (as long as everything else matches). Use ^ to match the beginning of a string, and $ to match the end. Note that if you do not wait for the end of a string, your responses can easily end up in the middle of the string as they are echoed from the spawned process. While still producing correct results, the output can look unnatural. Thus, use of $ is encouraged if you can exactly describe the characters at the end of a string.
- The -nocase flag causes uppercase characters of the output to compare as if they were lowercase characters. The pattern is not affected.
- While reading output, more than 2000 bytes can force
earlier bytes to be "forgotten". This may be changed with the
function match_max. (Note that excessively large values can slow
down the pattern matcher.) If patlist is full_buffer, the
corresponding body is executed if match_max bytes have been
received and no other patterns have matched. Whether or not the
full_buffer keyword is used, the forgotten characters are written
to expect_out(buffer).
expect "cd"
is as if the following statements had executed:set expect_out(0,string) cd set expect_out(buffer) abcd
and "efgh\n" is left in the output buffer. If a process produced the output "abbbcabkkkka\n", the result of:expect -indices -re "b(b*).*(k+)"
is as if the following statements had executed:set expect_out(0,start) 1 set expect_out(0,end) 10 set expect_out(0,string) bbbcabkkkk set expect_out(1,start) 2 set expect_out(1,end) 3 set expect_out(1,string) bb set expect_out(2,start) 10 set expect_out(2,end) 10 set expect_out(2,string) k set expect_out(buffer) abbbcabkkkk
and "a\n" is left in the output buffer. The pattern "*" (and -re ".*") will flush the output buffer without reading any more output from the process.
- Normally, the matched output is discarded from Expect's
internal buffers. This may be prevented by prefixing a pattern with the
-notransfer flag. This flag is especially useful in experimenting
(and can be abbreviated to "-not" for convenience while
experimenting).
expect { -i $proc2 busy {puts busy\n ; exp_continue} -re "failed|invalid password" abort timeout abort connected }
The value of the global variable any_spawn_id may be used to match patterns to any spawn_ids that are named with all other -i flags in the current expect command. The spawn_id from a -i flag with no associated pattern (i.e., followed immediately by another -i) is made available to any other patterns in the same expect command associated with any_spawn_id.
- This is useful for avoiding explicit loops or repeated
expect statements. The following example is part of a fragment to automate
rlogin. The exp_continue avoids having to write a second
expect statement (to look for the prompt again) if the rlogin
prompts for a password.
expect { Password: { stty -echo send_user "password (for $user) on $host: " expect_user -re "(.*)\n" send_user "\n" send "$expect_out(1,string)\r" stty echo exp_continue } incorrect { send_user "invalid password or account\n" exit } timeout { send_user "connection to $host timed out\n" exit } eof { send_user \ "connection to host failed: $expect_out(buffer)" exit } -re $prompt }
For example, the following fragment might help a user guide an interaction that is already totally automated. In this case, the terminal is put into raw mode. If the user presses "+", a variable is incremented. If "p" is pressed, several returns are sent to the process, perhaps to poke it in some way, and "i" lets the user interact with the process, effectively stealing away control from the script. In each case, the exp_continue allows the current expect to continue pattern matching after executing the current action.stty raw -echo expect_after { -i $user_spawn_id "p" {send "\r\r\r"; exp_continue} "+" {incr foo; exp_continue} "i" {interact; exp_continue} "quit" exit }
- By default, exp_continue resets the timeout timer. The timer is not restarted, if exp_continue is called with the -continue_timer flag.
- expect_after [expect_args]
- works identically to the expect_before except that if patterns from both expect and expect_after can match, the expect pattern is used. See the expect_before command for more information.
- expect_background [expect_args]
- takes the same arguments as expect, however it
returns immediately. Patterns are tested whenever new input arrives. The
pattern timeout and default are meaningless to
expect_background and are silently discarded. Otherwise, the
expect_background command uses expect_before and
expect_after patterns just like expect does.
- expect_before [expect_args]
- takes the same arguments as expect, however it
returns immediately. Pattern-action pairs from the most recent
expect_before with the same spawn id are implicitly added to any
following expect commands. If a pattern matches, it is treated as
if it had been specified in the expect command itself, and the
associated body is executed in the context of the expect command.
If patterns from both expect_before and expect can match,
the expect_before pattern is used.
expect_before -info -i $proc
At most one spawn id specification may be given. The flag -indirect suppresses direct spawn ids that come only from indirect specifications.
- expect_tty [expect_args]
- is like expect but it reads characters from /dev/tty (i.e. keystrokes from the user). By default, reading is performed in cooked mode. Thus, lines must end with a return in order for expect to see them. This may be changed via stty (see the stty command below).
- expect_user [expect_args]
- is like expect but it reads characters from stdin (i.e. keystrokes from the user). By default, reading is performed in cooked mode. Thus, lines must end with a return in order for expect to see them. This may be changed via stty (see the stty command below).
- fork
- creates a new process. The new process is an exact copy of the current Expect process. On success, fork returns 0 to the new (child) process and returns the process ID of the child process to the parent process. On failure (invariably due to lack of resources, e.g., swap space, memory), fork returns -1 to the parent process, and no child process is created.
- Forked processes exit via the exit command, just like the original process. Forked processes are allowed to write to the log files. If you do not disable debugging or logging in most of the processes, the result can be confusing.
- Some pty implementations may be confused by multiple readers and writers, even momentarily. Thus, it is safest to fork before spawning processes.
- interact [string1 body1] ... [stringn [bodyn]]
- gives control of the current process to the user, so that keystrokes are sent to the current process, and the stdout and stderr of the current process are returned.
- String-body pairs may be specified as arguments, in which case the body is executed when the corresponding string is entered. (By default, the string is not sent to the current process.) The interpreter command is assumed, if the final body is missing.
- If the arguments to the entire interact statement require more than one line, all the arguments may be "braced" into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces.
- For example, the following command runs interact with the
following string-body pairs defined: When ^Z is pressed, Expect is
suspended. (The -reset flag restores the terminal modes.) When ^A
is pressed, the user sees "you typed a control-A" and the
process is sent a ^A. When $ is pressed, the user sees the date. When ^C
is pressed, Expect exits. If "foo" is entered, the user
sees "bar". When ~~ is pressed, the Expect interpreter
runs interactively.
set CTRLZ \032 interact { -reset $CTRLZ {exec kill -STOP [pid]} \001 {send_user "you typed a control-A\n"; send "\001" } $ {send_user "The date is [clock format [clock seconds]]."} \003 exit foo {send_user "bar"} ~~ }
- In string-body pairs, strings are matched in the order they are listed as arguments. Strings that partially match are not sent to the current process in anticipation of the remainder coming. If characters are then entered such that there can no longer possibly be a match, only the part of the string will be sent to the process that cannot possibly begin another match. Thus, strings that are substrings of partial matches can match later, if the original strings that was attempting to be match ultimately fails.
- By default, string matching is exact with no wild cards.
(In contrast, the expect command uses glob-style patterns by
default.) The -ex flag may be used to protect patterns that might
otherwise match interact flags from doing so. Any pattern beginning
with a "-" should be protected this way. (All strings starting
with "-" are reserved for future options.)
interact -input $user_spawn_id timeout 3600 return -output \ $spawn_id
- During interact, raw mode is used so that all characters may be passed to the current process. If the current process does not catch job control signals, it will stop if sent a stop signal (by default ^Z). To restart it, send a continue signal (such as by "kill -CONT <pid>"). If you really want to send a SIGSTOP to such a process (by ^Z), consider spawning csh first and then running your program. On the other hand, if you want to send a SIGSTOP to Expect itself, first call interpreter (perhaps by using an escape character), and then press ^Z.
- String-body pairs can be used as a shorthand for avoiding having to enter the interpreter and execute commands interactively. The previous terminal mode is used while the body of a string-body pair is being executed.
- For speed, actions execute in raw mode by default. The -reset flag resets the terminal to the mode it had before interact was executed (invariably, cooked mode). Note that characters entered when the mode is being switched may be lost (an unfortunate feature of the terminal driver on some systems). The only reason to use -reset is if your action depends on running in cooked mode.
- The -echo flag sends characters that match the following pattern back to the process that generated them as each character is read. This may be useful when the user needs to see feedback from partially typed patterns.
- If a pattern is being echoed but eventually fails to match,
the characters are sent to the spawned process. If the spawned process
then echoes them, the user will see the characters twice. -echo is
probably only appropriate in situations where the user is unlikely to not
complete the pattern. For example, the following excerpt is from rftp, the
recursive-ftp script, where the user is prompted to enter ~g, ~p, or ~l,
to get, put, or list the current directory recursively. These are so far
away from the normal ftp commands, that the user is unlikely to type ~
followed by anything else, except mistakenly, in which case, they'll
probably just ignore the result anyway.
interact { -echo ~g {getcurdirectory 1} -echo ~l {getcurdirectory 0} -echo ~p {putcurdirectory} }
The -nobuffer flag sends characters that match the following pattern on to the output process as characters are read.proc lognumber {} { interact -nobuffer -re "(.*)\r" return puts $log "[clock format [clock seconds]]: dialed $interact_out(1,string)" } interact -nobuffer "atd" lognumber
- During interact, previous use of log_user is ignored. In particular, interact will force its output to be logged (sent to the standard output) since it is presumed the user doesn't wish to interact blindly.
- The -o flag causes any following key-body pairs to be applied to the output of the current process. This can be useful, for example, when dealing with hosts that send unwanted characters during a telnet session.
- By default, interact expects the user to be writing stdin and reading stdout of the Expect process itself. The -u flag (for "user") makes interact look for the user as the process named by its argument (which must be a spawned id).
- This allows two unrelated processes to be joined together without using an explicit loop. To aid in debugging, Expect diagnostics always go to stderr (or stdout for certain logging and debugging information). For the same reason, the interpreter command will read interactively from stdin.
- For example, the following fragment creates a login
process. Then it dials the user (not shown), and finally connects the two
together. Of course, any process may be substituted for login. A shell,
for example, would allow the user to work without supplying an account and
password.
spawn login set login $spawn_id spawn tip modem # dial back out to user # connect user to login interact -u $login
To send output to multiple processes, list each spawn id list prefaced by a -output flag. Input for a group of output spawn ids may be determined by a spawn id list prefaced by a -input flag. (Both -input and -output may take lists in the same form as the -i flag in the expect command, except that any_spawn_id is not meaningful in interact.) All following flags and strings (or patterns) apply to this input until another -input flag appears. If no -input appears, -output implies "-input $user_spawn_id -output". (Similarly, with patterns that do not have -input.) If one -input is specified, it overrides $user_spawn_id. If a second -input is specified, it overrides $spawn_id. Additional -input flags may be specified.
- interpreter [args]
- causes the user to be interactively prompted for Expect and Tcl commands. The result of each command is printed.
- Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. However return causes interpreter to return to its caller, while inter_return causes interpreter to cause a return in its caller. For example, if "proc foo" called interpreter which then executed the action inter_return, proc foo would return. Any other command causes interpreter to continue prompting for new commands.
- By default, the prompt contains two integers. The first integer describes the depth of the evaluation stack (i.e., how many times Tcl_Eval has been called). The second integer is the Tcl history identifier. The prompt can be set by defining a procedure called "prompt1" whose return value becomes the next prompt. If a statement has open quotes, parens, braces, or brackets, a secondary prompt (by default "+> ") is issued upon newline. The secondary prompt may be set by defining a procedure called "prompt2".
- During interpreter, cooked mode is used, even if the its caller was using raw mode.
- If stdin is closed, interpreter will return unless the -eof flag is used, in which case the subsequent argument is invoked.
- log_file [args] [[-a] file]
- If a filename is provided, log_file will record a
transcript of the session (beginning at that point) in the file.
log_file will stop recording if no argument is given. Any previous
log file is closed.
- log_user -info|0|1
- By default, the send/expect dialogue is logged to stdout
(and a logfile if open). The logging to stdout is disabled by the command
"log_user 0" and reenabled by "log_user 1". Logging to
the logfile is unchanged.
- match_max [-d] [-i spawn_id] [size]
- defines the size of the buffer (in bytes) used internally by expect. With no size argument, the current size is returned.
- With the -d flag, the default size is set. (The initial default is 2000.) With the -i flag, the size is set for the named spawn id, otherwise it is set for the current process.
- overlay [-# spawn_id] [-# spawn_id] [...] program [args]
- executes program args in place of the current Expect program, which terminates. A bare hyphen argument forces a hyphen in front of the command name as if it was a login shell. All spawn_ids are closed except for those named as arguments. These are mapped onto the named file identifiers.
- Spawn_ids are mapped to file identifiers for the new
program to inherit. For example, the following line runs chess and allows
it to be controlled by the current process - say, a chess master.
overlay -0 $spawn_id -1 $spawn_id -2 $spawn_id chess
This is more efficient than "interact -u", however, it sacrifices the ability to do programmed interaction since the Expect process is no longer in control.
- Note that no controlling terminal is provided. Thus, if you disconnect or remap standard input, programs that do job control (shells, login, etc) will not function properly.
- parity [-d] [-i spawn_id] [value]
- defines whether parity should be retained or stripped from the output of spawned processes. If value is zero, parity is stripped, otherwise it is not stripped. With no value argument, the current value is returned.
- With the -d flag, the default parity value is set. (The initial default is 1, i.e., parity is not stripped.) With the -i flag, the parity value is set for the named spawn id, otherwise it is set for the current process.
- remove_nulls [-d] [-i spawn_id] [value]
- defines whether nulls are retained or removed from the output of spawned processes before pattern matching or storing in the variable expect_out or interact_out. If value is 1, nulls are removed. If value is 0, nulls are not removed. With no value argument, the current value is returned.
- With the -d flag, the default value is set. (The
initial default is 1, i.e., nulls are removed.) With the -i flag,
the value is set for the named spawn id, otherwise it is set for the
current process.
- send [-flags] string
- Sends string to the current process. For example,
the command
send "hello world\r"
sends the characters, h e l l o <blank> w o r l d <return> to the current process. (Tcl includes a printf-like command (called format) which can build arbitrarily complex strings.)
- Characters are sent immediately although programs with
line-buffered input will not read the characters until a return character
is sent. A return character is denoted "\r".
set send_human {.1 .3 1 .05 2} send -h "I'm hungry. Let's do lunch."
while the following might be more suitable after a hangover:set send_human {.4 .4 .2 .5 100} send -h "Goodd party lash night!"
Note that errors are not simulated, although you can set up error correction situations yourself by embedding mistakes and corrections in a send argument.# To avoid giving hackers hints on how to break in, # this system does not prompt for an external password. # Wait for 5 seconds for exec to complete spawn telnet very.secure.gov sleep 5 send password\r
exp_send is an alias for send. If you are using Expectk or some other variant of Expect in the Tk environment, send is defined by Tk for an entirely different purpose. exp_send is provided for compatibility between environments. Similar aliases are provided for other Expect's other send commands.
- send_error [-flags] string
- is like send, except that the output is sent to stderr rather than the current process.
- send_log [--] string
- is like send, except that the string is only sent to the log file (see log_file.) The arguments are ignored if no log file is open.
- send_tty [-flags] string
- is like send, except that the output is sent to /dev/tty rather than the current process.
- send_user [-flags] string
- is like send, except that the output is sent to stdout rather than the current process.
- sleep seconds
- causes the script to sleep for the given number of seconds. Seconds may be a decimal number. Interrupts (and Tk events if you are using Expectk) are processed while Expect sleeps.
- spawn [args] program [args]
- creates a new process running program args. Its stdin, stdout and stderr are connected to Expect, so that they may be read and written by other Expect commands. The connection is broken by close or if the process itself closes any of the file identifiers.
- When a process is started by spawn, the variable spawn_id is set to a descriptor referring to that process. The process described by spawn_id is considered the current process. spawn_id may be read or written, in effect providing job control.
- user_spawn_id is a global variable containing a
descriptor which refers to the user. For example, when spawn_id is
set to this value, expect behaves like expect_user.
- tty_spawn_id is a global variable containing a
descriptor which refers to /dev/tty. If /dev/tty does not exist (such as
in a cron, at, or batch script), then tty_spawn_id is not defined.
This may be tested as:
if {[info vars tty_spawn_id]} { # /dev/tty exists } else { # /dev/tty doesn't exist # probably in cron, batch, or at script }
- spawn returns the UNIX process id. If no process is spawned, 0 is returned. The variable spawn_out(slave,name) is set to the name of the pty slave device.
- By default, spawn echoes the command name and arguments. The -noecho flag stops spawn from doing this.
- The -console flag causes console output to be
redirected to the spawned process. This is not supported on all systems.
- Normally, spawn takes little time to execute. If you
notice spawn taking a significant amount of time, it is probably
encountering ptys that are wedged. A number of tests are run on ptys to
avoid entanglements with errant processes. (These take 10 seconds per
wedged pty.) Running Expect with the -d option will show if
Expect is encountering many ptys in odd states. If you cannot kill
the processes to which these ptys are attached, your only recourse may be
to reboot.
- strace level
- causes following statements to be printed before being
executed. (Tcl's trace command traces variables.) level indicates
how far down in the call stack to trace. For example, the following
command runs Expect while tracing the first 4 levels of calls, but
none below that.
expect -c "strace 4" script.exp
- stty args
- changes terminal modes similarly to the external stty
command.
- The following example illustrates how to temporarily
disable echoing. This could be used in otherwise-automatic scripts to
avoid embedding passwords in them. (See more discussion on this under
EXPECT HINTS below.)
stty -echo send_user "Password: " expect_user -re "(.*)\n" set password $expect_out(1,string) stty echo
- system args
- gives args to sh(1) as input, just as if it had been typed as a command from a terminal. Expect waits until the shell terminates. The return status from sh is handled the same way that exec handles its return status.
- In contrast to exec which redirects stdin and stdout to the script, system performs no redirection (other than that indicated by the string itself). Thus, it is possible to use programs which must talk directly to /dev/tty. For the same reason, the results of system are not recorded in the log.
- timestamp [args]
- returns a timestamp. With no arguments, the number of
seconds since the epoch is returned.
%a abbreviated weekday name %A full weekday name %b abbreviated month name %B full month name %c date-time as in: Wed Oct 6 11:45:56 1993 %d day of the month (01-31) %H hour (00-23) %I hour (01-12) %j day (001-366) %m month (01-12) %M minute (00-59) %p am or pm %S second (00-61) %u day (1-7, Monday is first day of week) %U week (00-53, first Sunday is first day of week one) %V week (01-53, ISO 8601 style) %w day (0-6) %W week (00-53, first Monday is first day of week one) %x date-time as in: Wed Oct 6 1993 %X time as in: 23:59:59 %y year (00-99) %Y year as in: 1993 %Z timezone (or nothing if not determinable) %% a bare percent sign
Other % specifications are undefined. Other characters will be passed through untouched. Only the C locale is supported.
- trap [[command] signals]
- causes the given command to be executed upon future
receipt of any of the given signals. The command is executed in the global
scope. If command is absent, the signal action is returned. If
command is the string SIG_IGN, the signals are ignored. If
command is the string SIG_DFL, the signals are result to the system
default. signals is either a single signal or a list of signals.
Signals may be specified numerically or symbolically as per signal(3). The
"SIG" prefix may be omitted.
trap exit {SIGINT SIGTERM}
If you use the -D flag to start the debugger, SIGINT is redefined to start the interactive debugger. This is due to the following trap:trap {exp_debug 1} SIGINT
The debugger trap can be changed by setting the environment variable EXPECT_DEBUG_INIT to a new trap command.if {![exp_debug]} {trap mystuff SIGINT}
Alternatively, you can trap to the debugger using some other signal.
- wait [args]
- delays until a spawned process (or the current process if none is named) terminates.
- wait normally returns a list of four integers. The
first integer is the pid of the process that was waited upon. The second
integer is the corresponding spawn id. The third integer is -1 if an
operating system error occurred, or 0 otherwise. If the third integer was
0, the fourth integer is the status returned by the spawned process. If
the third integer was -1, the fourth integer is the value of errno set by
the operating system. The global variable errorCode is also set.
- The -i flag declares the process to wait
corresponding to the named spawn_id (NOT the process id). Inside a SIGCHLD
handler, it is possible to wait for any spawned process by using the spawn
id -1.
LIBRARIES¶
Expect automatically knows about two built-in libraries for Expect scripts. These are defined by the directories named in the variables exp_library and exp_exec_library. Both are meant to contain utility files that can be used by other scripts.PRETTY-PRINTING¶
A vgrind definition is available for pretty-printing Expect scripts. Assuming the vgrind definition supplied with the Expect distribution is correctly installed, you can use it as:vgrind -lexpect file
EXAMPLES¶
It many not be apparent how to put everything together that the man page describes. I encourage you to read and try out the examples in the example directory of the Expect distribution. Some of them are real programs. Others are simply illustrative of certain techniques, and of course, a couple are just quick hacks. The INSTALL file has a quick overview of these programs. The Expect papers (see SEE ALSO) are also useful. While some papers use syntax corresponding to earlier versions of Expect, the accompanying rationales are still valid and go into a lot more detail than this man page.CAVEATS¶
Extensions may collide with Expect's command names. For example, send is defined by Tk for an entirely different purpose. For this reason, most of the Expect commands are also available as "exp_XXXX". Commands and variables beginning with "exp", "inter", "spawn", and "timeout" do not have aliases. Use the extended command names if you need this compatibility between environments.BUGS¶
It was really tempting to name the program "sex" (for either "Smart EXec" or "Send-EXpect"), but good sense (or perhaps just Puritanism) prevailed.set env(TERM) vt100
set env(SHELL) /bin/sh set env(HOME) /usr/bin
spawn date sleep 20 expectwill fail. To avoid this, invoke non-interactive programs with exec rather than spawn. While such situations are conceivable, in practice I have never encountered a situation in which the final output of a truly interactive program would be lost due to this behavior.
send "speed 9600\r"; sleep 1 expect { timeout {send "\r"; exp_continue} $prompt }
EXPECT HINTS¶
There are a couple of things about Expect that may be non-intuitive. This section attempts to address some of these things with a couple of suggestions.set prompt "(%|#|\\$) $" ;# default prompt catch {set prompt $env(EXPECT_PROMPT)} expect -re $promptI encourage you to write expect patterns that include the end of whatever you expect to see. This avoids the possibility of answering a question before seeing the entire thing. In addition, while you may well be able to answer questions before seeing them entirely, if you answer early, your answer may appear echoed back in the middle of the question. In other words, the resulting dialogue will be correct but look scrambled.
SEE ALSO¶
Tcl(3), libexpect(3)AUTHOR¶
Don Libes, National Institute of Standards and TechnologyACKNOWLEDGMENTS¶
Thanks to John Ousterhout for Tcl, and Scott Paisley for inspiration. Thanks to Rob Savoye for Expect's autoconfiguration code. The HISTORY file documents much of the evolution of expect. It makes interesting reading and might give you further insight to this software. Thanks to the people mentioned in it who sent me bug fixes and gave other assistance. Design and implementation of Expect was paid for in part by the U.S. government and is therefore in the public domain. However the author and NIST would like credit if this program and documentation or portions of them are used.29 December 1994 |