Turn: expect the basic usage

2011-03-19  来源:本站原创  分类:OS  人气:146 

First, an overview

Shell we can achieve a simple control flow functions, such as: cycling, judgments. But you need to interact with the occasion to intervene must be artificial, and sometimes we may need to implement and interactive programs such as telnet server for interactive features. The Expect to achieve this functionality on the use of tools.

Expect is a language free programming tools, automatic and interactive tasks to communicate without human intervention. Expect the author of Don Libes Expect in 1990 when writing Expect to do the following definitions: Expect is a tool for automatic interactive features of the software suite (Expect [is a] software suite for automating interactive tools). System administrators can use it to create scripts used to implement a command or program to provide input, and these commands and procedures is expected from the terminal (terminal) to get input, these inputs are generally carried out manually input. Expect the program can prompt the standard input to the analog input to the program need to interact program execution. Can achieve even a simple BBS chat robot. :)

Expect is growing, as time goes by, the more powerful, has become a powerful system administrator's assistant. Expect requires Tcl programming language support, Expect to be running on the system must first install Tcl.

Two, Expect works

From the simplest level it, Expect work as a common tool of the Chat script. Chat script for the first UUCP network to be used to achieve the need to establish a connection between the computer when a particular login session automation.

Chat script is a series of expect-send pairs: expect to wait for specific characters in the output of the output, usually a prompt to send a specific response. For example, the following Chat script to achieve the standard output there waiting Login: string, and then send somebody as a user name; and then wait for the Password: prompt, and issue a response sillyme.


Login: somebody Password: sillyme

This script is used to implement a login process with a specific username and passwords login.

Expect the simplest mode of operation is essentially the same script Chat script mode is the same.

1, we analyze the following functions to achieve a response chsh command script. We first look at the interactive command format. Suppose we want to change the login script for user chavez, required to achieve the command interaction is as follows:


# Chsh chavez
Changing the login shell for chavez
Enter the new value, or press return for the default
Login Shell [/ bin / bash]: / bin / tcsh

You can see the first output of a number of command-line prompt information and prompts the user a new login shell. We must enter the message behind the user's login shell, or directly enter does not modify the login shell.

2, the following is a can be used to automatically execute the command of Expect script:

  1. #! / Usr / bin / expect
  2. # Change a login shell to tcsh
  3. set user [lindex $ argv 0]
  4. spawn chsh $ user
  5. expect "]:"
  6. send "/ bin / tcsh"
  7. expect eof
  8. exit

Copy code

This simple script can explain many features Expect program. And other scripts as the first line specifies the command used to execute the script program, here is the / usr / bin / expect. Procedures used to obtain the first line of the script execution parameters (save in the array $ argv, the argument begins from 0), and save it to a variable in the user.

Expect the second parameter used to start the script spawn command and command of the conversation, here is the chsh command to start, in fact, the way the command is Yansheng Zi process to run.

Subsequent expect and send commands to achieve the interaction. First of all there waiting for the output script]: string, once appeared in the output characteristics of chsh output to a string (the string is often to wait for the general characteristics of the final prompt enter the characteristics of information). For other information will not match completely ignored. When the script is the characteristic string, expect to send / bin / tcsh and a carriage return to the chsh command. Finally, the script waits for the command exits (chsh end), once to identify the child process receives the eof character is over, expect the end of the script will exit.

3, to decide how to respond to

Administrators often have such needs, hopes the current specific situation in different ways to respond to a command. We can expect the following examples to see the conditions can be very complex response, but only by a simple modification can be achieved pre-processing script. The following example is a more complex example of expect-send:

  1. expect-re "\ [(.*)]:"
  2. if {$ expect_out (1, string )!="/ bin / tcsh "} {
  3. send "/ bin / tcsh"}
  4. send ""
  5. expect eof

Copy code

In this example, the first command now uses an expect-re argument, which indicates that the specified string is a regular expression, rather than an ordinary string. For the above example is to find a left bracket character (which must be carried out three times to escape (escape), so there are three symbols, and expect it to for both the regular expression special characters) followed by zero or more character, and finally a right parenthesis character. Where .* indicates that one or more of any character and store it in () is due to the match result is stored in a variable in order to achieve the results of the subsequent visit of the match.

When a match is found, check included in the [] in the string to see whether / bin / tcsh. If not, then send / bin / tcsh to the chsh command as input, if it is just to send a carriage return. This simple issue of phase-specific response of the small example illustrates the power of expect.

In a regular expression, you can () contains a number of parts and access them via expect_out array. Various parts of the expression encoded from left to right, starting at 1 (0 contains the matched output). () May be nested, and this case code from the innermost to the outermost layer for the.

4, the use of overtime

The following example will be described with an expect prompt timeout function. The script prompts the user, if given time there is no input, it will timeout and return a default response. This script takes three parameters: prompt string, the default response, and timeout (seconds).

  1. #! / Usr / bin / expect
  2. # Prompt function with timeout and default.
  3. set prompt [lindex $ argv 0]
  4. set def [lindex $ argv 1]
  5. set response $ def
  6. set tout [lindex $ argv 2]

Copy code

The first part of the first script to be run parameters and save them to internal variables.

  1. send_tty "$ prompt:"
  2. set timeout $ tout
  3. expect "" {
  4. set raw $ expect_out (buffer)
  5. # Remove final carriage return
  6. set response [string trimright "$ raw" ""]
  7. }
  8. if {"$ response" == "} {set response $ def}
  9. send "$ response"
  10. # Prompt function with timeout and default.
  11. set prompt [lindex $ argv 0]
  12. set def [lindex $ argv 1]
  13. set response $ def
  14. set tout [lindex $ argv 2]

Copy code

This is the rest of the contents of the script. You can see send_tty command displayed on the terminal used to achieve prompt string and a colon and space. after the set timeout command to set all of the expect command waits for a response timeout for the $ tout (-l parameter is used to close any timeout setting).

Then expect to wait for the command output appears on the carriage return character. If you get a carriage return before the timeout, then the set command will assign the user to input the contents of the face raw. Then the command will be entered by the user to remove the contents of the final carriage return after the assignment to the variable response.

Then, if the response is empty in the response value will be set to the default value (if the user did not enter after the timeout or the user just entered a carriage return). Finally, send the command to the response variable value plus the carriage return sent to standard output.

One interesting thing is that the script does not use the spawn command. The expect script calls the script with any process of interaction.

If the script is named prompt, then it can be used in any C-style shell.

% Set a = 'prompt "Enter an answer" silence 10'
Enter an answer: test

% Echo Answer was "$ a"
Answer was test
prompt set timeout to 10 seconds. If the timeout or the user just entered a carriage return, echo command will output

Answer was "silence"

5, a more complex example

Here we will discuss a more complex example expect script, this script uses some of the more complex control structure and a number of complex interactions. This example sends a write command to be used to implement any of the user, send a message from a file or from keyboard input.

  1. #! / Usr / bin / expect
  2. # Write to multiple users from a prepared file
  3. # Or a message input interactively
  4. if {$ argc <2} {
  5. send_user "usage: $ argv0 file user1 user2 ..."
  6. exit
  7. }

Copy code

send_user command to display Help information to the parent process (usually the user's shell) of the standard output.

  1. set nofile 0
  2. # Get filename via the Tcl lindex function
  3. set file [lindex $ argv 0]
  4. if {$ file == "i"} {
  5. set nofile 1
  6. } Else {
  7. # Make sure message file exists
  8. if {[file isfile $ file]! = 1} {
  9. send_user "$ argv0: file $ file not found."
  10. exit}}

Copy code

This part of the script starts with processing parameters, it must be a store to send the message that the file name or use the interactive content of the input to be sent consumers the "i" command.

Variable file is set to script the first parameter value is a Tcl lindex function to achieve the function from the list / array to get a specific element. [] Used to implement the function return value of lindex command as a set of parameters.

If the script's first argument is a lowercase "i", then the variable is set to 1 nofile, or by calling the Tcl functions isfile to verify the parameters specified file exists, if there is no exit on error.

Here you can see if the command used to implement logic functions. The command is followed directly with the judge conditions and perform in determining the conditions within the {} command. if condition is false, then after running the else block.

  1. set procs {}
  2. # Start write processes
  3. for {set i 1} {$ i <$ argc}
  4. {Incr i} {
  5. spawn-noecho write
  6. [Lindex $ argv $ i]
  7. lappend procs $ spawn_id
  8. }

Copy code

Last part of the write start using the spawn command to send a message to the user process to achieve. This command is used for control functions to achieve the cycle, the loop variable is first set to 1, and so increase. Loop is the last of the contents of {}. Here we are with the script of the second and subsequent arguments to spawn a write command and sends a message each parameter as the user name. lappend command to save each spawn the process using the process ID number of the internal variable $ spawn_id procs in Variable construct a list of process ID number.

  1. if {$ nofile == 0} {
  2. setmesg [open "$ file" "r"]
  3. } Else {
  4. send_user "enter message,
  5. ending with ^ D: "}

Copy code

Finally, the script to achieve the value of the variable nofile open message file or prompt the user to send a message.

  1. set timeout -1
  2. while 1 {
  3. if {$ nofile == 0} {
  4. if {[gets $ mesg chars] == -1} break
  5. set line "$ chars"
  6. } Else {
  7. expect_user {
  8. -Re "" {}
  9. eof break}
  10. set line $ expect_out (buffer)}
  11. foreach spawn_id $ procs {
  12. send $ line}
  13. sleep 1}
  14. exit

Copy code

The above code shows how the actual message text is sent through an infinite loop while the. while loop to determine if the message is how to get. In non-interactive mode, the contents of the next line read from the message file when the file content at the end of the while loop will be over. (Break command terminates the loop to achieve).

In interactive mode, expect_user order to receive messages from the user when the user enters ctrl + D at the end of the input, while the end of cycle. Both cases the variable $ line are used to hold the next line of the message content. When a message file, enter the message will be attached to the tail.

spawn foreach loop through all the processes, these processes the list of ID numbers are stored in the variable $ procs in, respectively, and various processes to achieve communication. send command form the foreach loop, sending a message to the current line of the write process. The final while loop is a sleep command is mainly used to handle the case of non-interactive mode, to ensure that the message is not too fast, sending it to each write process. When the while loop exits, expect the script ends.

Third, the reference resource

Expect deep version of the software script with many examples, not only can expect to learn and understand the script, and is very use of tools. Generally in / usr / doc / packages / expect / example to see them in some linux release some expect scripts in / usr / bin directory.

Don Libes, Exploring Expect, O'Reilly & Associates, 1995.

John Ousterhout, Tcl and the Tk Toolkit, Addison-Wesley, 1994.

Some useful expect script

autoexpect: This script will run according to their operation when the user generates an expect script. Its function is somewhat analogous to the Emacs editor's keyboard macro tool. Automatically create a script to create your own custom scripts may be a good start.

kibitz: This is a very useful tool. Through which two or more users can connect to the same shell process.

tkpasswd: This script provides a GUI tool to change user passwords, including the ability to check whether the password is a dictionary-based model. This tool is also a good learning example expect and tk.



Created :2001 -04-29
Article attributes: reproduced Source: China Science and BBS Station article submission: quack (quack_at_xfocus.org)


Copyright (c) 1999

This tutorial by * gourd * translation, and made the appropriate changes can be freely used for non-commercial purposes.
But Redistribution must copy the [copyright].


Many parts of the translation is not done "letter." Of course, no time to do, "Ya" I hope you understand.


Don Libes: National Institute of Standards and Technology
[email protected]


1 Summary 2 keyword 3 Introduction 4.Expect review 5.callback
6.passwd and consistency checks 7.rogue and pseudo-terminal 8.ftp
10 multi-process control: job control 11. Interactive use Expect
12. Expect interactive programming 13. Non-interactive control of the program 14.Expect speed 15 security concerns 16.Expect resources 17. Reference books

1. [Abstract]

Modern Shell's process provides minimal control (starting, stopping, etc.), while leaving the interactive features of the user. This means that some programs, you can not run non-interactively, such as passwd. There are programs that run non-interactively, but to a large extent the loss of flexibility, such as fsck. This indicates the beginning of Unix tools to construct logical problems. Expect some of them just to fill the cracks in the Unix environment to solve the long-term existence of some problems.

Expect uses Tcl as the core language. Not only that, regardless of the program is interactive or non-interactive and, Expect can be used. This is a small language and other Unix tools together with a strong feature of the classic examples.

Expect this part of the tutorial is not about implementation, but about Expect the use of language itself, which is largely described through examples of different scripts to reflect. One of the few examples also exemplify Expect several new features.

2 [keyword]

Expect, interactive, POSIX, process-oriented dialogue, Shell, Tcl, Unix;

3. [Introduction]

Called the Unix file system check fsck program, which can be used from the Shell-y or-n option to perform. In the manual [1] which,-y option is defined like this.

"For all the problems are assumed to fsck a" yes "response; in such use, must be particularly careful because it actually allows the program to continue to run unconditionally, even had some very serious error"

In contrast,-n option to secure more, but it is actually almost just did. This interface is very bad, but there are many programs that style. Ftp file transfer program has an option to disable interactive questions to run from inside a script. But once an error has occurred, it did not provide measures to deal with.

Expect is a tool for controlling interactive programs. He solved the fsck problem with non-interactive way to achieve all of the interactive features. Fsck is not designed specifically for Expect, it can also be a similar ftp error handling.

fsck and ftp problems to show us like sh, csh and other shell provides a number of user interface limitations. Shell did not provide a program from a program like reading and writing capabilities. This means that the shell can run fsck fsck but only at the expense of flexibility to do as part of the cost. Some programs simply can not be executed. For example, if you do not have a user interface to provide interactive input, it can not run forever. Other well as Telnet, crypt, su, rlogin and other procedures which can not be automated in a shell script. There are many other applications is also required in the design of user input.

Expect to be designed to specifically interact with the needle and interactive programs. Expect a programmer can write a script to describe the procedures and user dialogue. Expect the program can then run non-interactive "interactive" process. Write an interactive program script and write the script non-interactive program is as simple. Expect can also be used to automate part of the dialogue, because the control of the program can switch between the keyboard and the script.

bes [2] which has a detailed description. Simply put, the script is written in an interpreted language. (Also C and C + +, Expect libraries available, but this is beyond the scope of this article). Expect the process for creating interactive and read-write their input and output commands. Expect the same name as one of its command and named.

Expect is a Tcl-based language. Tcl is actually a subroutine library, the subroutine library can be embedded into the program in order to provide language services. The final language is something like a typical Shell language. Inside the set command to assign a variable to control program execution if, for, continue, etc. commands, but also for general math and string operations. Of course, you can use exec to invoke Unix programs. All of these features, Tcl has. Tcl in the reference books Outerhour [3] [4], there are detailed descriptions.

Expect is a Tcl builds on, and it also provides some Tcl does not have command. spawn command to activate a Unix program for interactive operation. send command to send a process a string. the process of expect to wait for some of the strings. support regular expressions and can expect to wait for multiple strings simultaneously, and each string to perform different operations. expect also to understand some special cases, such as overtime and end of the file.

The case of expect and Tcl command style is very similar. Are used to match a string more than one string. (Whenever possible, new orders and existing Tcl command is always similar to making the tools to keep the language family inheritance). The following is the definition of expect from the manual [5] on the excerpt down.

expect patlist1 action1 patlist2 action2 .....

The command wait until the current process output and more than one pattern matches, or wait until more than a certain length of time, or wait until the end of file encountered.

If the last action is empty, you can omit it.

Each patlist by a pattern or model of the table (lists) component. If a pattern is matched, the corresponding action is executed. Expect to return from the implementation of the results.
The string is an exact match (or when the timeout occurs, the match has been read but not the string) is stored in the variable expect_match inside. If patlist is eof or timeout, or timeout occurs when the end of the file to perform the corresponding action. Usually the time when the timeout is 10 seconds, but can use a similar "set timeout 30" kind of command to set a time out 30 seconds.

The following block is the login script from a removal of the inside. abort is defined elsewhere in the script process, while others use a similar action with the C language Tcl primitives.

expect "* welcome *" break
"* Busy *" {print busy; continue}
"* Failed *" abort
timeout abort

Mode is usually the C Shell-style regular expressions. Pattern must match the current process from the beginning of an expect or interact all the output (so use the wildcard character * is) common. However, once the output of more than 2000 bytes in front of the character will be forgotten, this value can be set match_max to change.

expect command does reflect the language of the best and expect the worst of nature. In particular, expect the flexibility of command is often confusing syntax to do the price. In addition to keyword patterns (for example, eof, timeout) that mode table can include multiple modes. This guarantee provides a way to distinguish them. However, these tables require additional separate scans, if not properly used ["] enclosed, which will be treated as blank characters and because of the string Tcl provides two reference methods: single quotes and double quotes, the situation has changed the worse. (in Tcl which, if not ambiguous, then there is no need to use quotation marks) in the manual expect inside, there is a separate part to explain this complexity. fortunately: there are some very seems to prevent a good example of this complaint, but this complexity is likely in future versions of the re-emergence. To enhance readability, in this article, provided the script assume that double quotes is enough.

You can use the backslash character to separate references, the backslash is also used for the continuation of the statement, if not a backslash at the end of the statement to a line on the end. This is consistent, and Tcl. Tcl found in open single quotation marks or double quotation marks when opened will continue scanning. Moreover, the semicolon can be used to separate multiple statements on one line. This may sound a bit confusing, but it is an interpreted language style, but this is indeed a very beautiful part of Tcl.

5. [Callback]

It is very surprising is that some small scripts to the production of useful features. Here is a dial phone number of the script. He used to reverse the charges, in order to make long-distance telephone billing computer. This script uses a similar "expect callback.exp 12016442332" to activate. Among them, the name of the script is callback.exp, and +1 (201) 644-2332 is the phone number to dial.

# First give the user some time to logout
exec sleep 4
spawn tip modem
expect "* connected *"
send "ATD [llindex $ argv 1]"
# Modem takes a while to connect
set timeout 60
expect "* CONNECT *"

The first line is a comment, the second line shows how to call Unix programs do not interact. sleep 4 causes the program to block four seconds to make the user time to exit, because the modem will always call back the user has to use the phone number.

The following line tip using spawn command to activate the program, in order to make the tip of the output can be expect to read, making the tip from the send read input. Once it has been connected to the tip, modem will be asked to call the Big Brother phone number. (Assuming the modem is Hayes compatible, but the script can be easily modified to adapt to other types of modem). No matter what happens, expect will be terminated. If the call fails, expect script can be designed to be retried, but there is no. If the call succeeds, getty will expect the withdrawal to detect DTR, and prompt the user loging:. (Useful tend to provide more error checking.)

This script shows the use of command line arguments, command-line parameters are stored in a table called argv inside (This is much like C-style). In this case, the first element is the phone number. Are enclosed in square brackets so as part of the command to execute, the result is replaced by the enclosed part. It is also much like the style of the C Shell.

The script and a C-language program of about 60K to achieve similar functionality.

6. [Passwd and consistency checks]

Earlier, we mentioned that the passwd program in the absence of user interaction, can not run, passwd ignores I / O redirection, it can not be embedded inside the pipe to another program or file from the read input. The program insisted that the real interaction with the user. For security reasons, passwd is designed to be so, but the result is no way to test non-interactive passwd. Such a safety-critical procedures of the system is not even a reliable way to test the real irony.

passwd to a user name as a parameter, interactive prompt for a password. The following expect script to a user name and password as a parameter rather than the interactive operation.

spawn oasswd [lindex $ argv 1]
set password [lindex $ argv 2]
expect "* password:"
send "$ password"
expect "* password:"
send "$ password"
expect eof

The first line starts with the user name as an argument the passwd program, for convenience, the second line to the password stored in a variable. And the shell is similar to the variable does not need the use of advance statements.

In the third line, expect the search pattern "* password:", which * allows match any input, so all the details specified in terms of avoiding it is very effective. The above program is not action, so expect to detect the pattern continued after the operation.

Upon receiving the prompt, put the password on the next line sent to the current process. That enter. (In fact, all about the character of the C conventions are supported). The above program has two expect-send sequences because passwd in order to confirm the input, requiring twice the input. In non-interactive program which, it is unnecessary, but the assumption that passwd is in and user interaction, so our script is done.

Finally, "expect eof" The role of this line is the output of the search in the passwd file terminator, the line of the statement also shows the keyword matching. Another keyword matching is a timeout, timeout is used to indicate the failure of all the matches and the length of time a specific match. Eof here is very necessary because the passwd is designed to be checking all of its I / O are all successful, including the second password generated when the last new line.

This script has enough to show the basic interactive passwd command. Another example of a more complete back to check some of the other acts. For example, the following script will be able to check the passwd program in other areas. All tips were examined. Inspection of the waste input has been properly handled. The process of death, unusually slow response, or other unexpected behavior to deal with.

spawn passwd [lindex $ argv 1]
expect eof {exit 1}
timeout {exit 2}
"* No such user .*" {exit 3}
"* New password:"
send "[lindex $ argv 2"
expect eof {exit 4}
timeout {exit 2}
"* Password too long *" {exit 5}
"* Password too short *" {exit 5}
"* Retype ew password:"
send "[lindex $ argv 3]"
expect timeout {exit 2}
"* Mismatch *" {exit 6}
"* Password unchanged *" {exit 7}
expect timeout {exit 2}
"*" {Exit 6}

The script exits with a number to indicate what happened. 0 indicates normal operation of the passwd program, said the unexpected death of 1, 2 that lock, and so on. Number is used for simplicity. expect to return a string and returns the number is as simple, even if the program is derived from self-generated news is the same. In fact, the typical approach is to keep the whole interaction process to a file inside, only when the program runs as expected when only then delete the file. Otherwise, this log is left after further examination.

This script is designed to check the passwd from the other scripts to drive. This second script to read from a file inside the parameters and the expected results. For each input parameter set, it calls the first script and the results and compare the expected results. (Because this task non-interactive, a plain old shell can be used to explain the second script). For example, a data file passwd is likely the same as below.

passwd.exp 3 bogus - -
passwd.exp 0 fred abledabl abledabl
passwd.exp 5 fred abcdefghijklm -
passwd.exp 5 fred abc -
passwd.exp 6 fred foobar bar
passwd.exp 4 fred ^ C -

The first domain name is the return of scripts to be run. The second domain is necessary and the results match the exit value. The third domain is the user name. The fourth and fifth domain is the domain should be prompted to enter the password. Minus sign indicates there is only one domain, this domain is absolutely not needed. In the first line, bogus user name that is illegal, so passwd will respond to that: no such user. expect returns on exit is just the second field 3,3. In the last line, ^ C is to be given practical application to verify whether it was appropriate to exit the program.

In this way, expect can be used to test and debug interactive software, this is precisely the IEEE POSIX 1003.2 (shell and tools) required by the consistency test. Further instructions, please refer Libes [6].

7. [Rogue and the pseudo terminal]

Unix users would come through the pipeline and other processes linked to the way a very familiar (for example: a shell pipe). expect to use pseudo-terminals linked to the process and derive. Pseudo-terminal provides semantics so that the program end and true that they are terminal I / O operations.

For example, BSD adventure game rogue alive mode, and assume the other end of the connection is a character addressable terminal. Programming can expect to make by using the user interface can play this game.

This adventure game rogue first provide you with a variety of physical properties, such as the power value of the role. Most of the time, the power values are 16, but 20 times in almost every power which will have a value of 18. A lot of rogue players know this, but no one wants to start the program 20 times to get a good configuration. The following script will be able to achieve this goal.

for {} {1} {} {
spawn rogue
expect "* Str: 18 *" break
"* Str: 16 *"

The first line is a for loop, and C language control the format is like. rogue starts, expect to see on the inspection force value is 18 or 16, if it is 16, the program will close and wait through the execution to exit. The role of these two commands are turned off and the pseudo terminal connection and wait for the process to exit. rogue read a file character on the launch, so the loop continues to run, resulting in a new rogue game to check.

When a value of 18 to find the configuration, the control loop and jump on the launch of the last line of the script. interact to transfer control to the user so that they can play this particular game.

Imagine this script to run. You can really see is 20 or 30 initial configuration in less than a second time across the screen, and finally you're left with is a game with good configuration. The only better way than this is to use debugging tools to play the game.

Is necessary that we recognize this point: rogue is a game with the graphics cursor. expect the programmer must understand: the cursor movement is not necessarily in an intuitive way to reflect on the screen. Fortunately, in our case, this is not a problem. Expect improvements in the future of the may include a built-in graphics area to support the character of the terminal emulator.

8. [Ftp]

We expect to use to write the first script does not print out "Hello, World". In fact, it implements some of the more useful features. It through non-interactive way to run ftp. ftp is used to support TCP / IP network on the file transfer process. In addition to some simple function, the general realization require user involvement.

The following script from a host to use anonymous ftp to remove a file. Among them, the host name is the first parameter. Filename is the second parameter.

spawn ftp [lindex $ argv 1]
expect "* Name *"
send "anonymous"
expect "* Password: *"
send [exec whoami]
expect "* ok * ftp> *"
send "get [lindex $ argv 2]"
expect "* ftp> *"

This program is designed above in the background ftp. Although they use and expect a similar underlying mechanism, but left to improve their programmability. Expect to provide a high-level language because you can modify it to meet your specific needs. For example, you can add the following features:

: Insist - if the connection or transmission failure, you can per hour or per minute, or even according to other factors such as user load, to carry out from time to time and try again.
: Notification - transmission by mail, write to inform you of other programs or even notice the failure.
: Initialization - Each user can have their own high-level language initialization file (for example,. Ftprc). This C shell On . Cshrc use very similar.

expect can also perform other more complex tasks. For example, he can use the Archie McGill University system. Archie is an anonymous Telnet service, which provides for the description of the Internet can be obtained via anonymous ftp access to the database file. By using this service, the script can ask Archie to a specific location of the file, and it taken down from the ftp server. This feature is only required to achieve the above few lines of script that you can.

Now there is no known background-ftp functions to achieve the above number, can not say that all function. In expect inside, its implementation is very simple. "Adhere" to achieve the expect script which only requires a loop. "Notice" can be realized as long as the implementation of mail and write on it. "Initialization file" can be realized using a single command, source. Ftprc, can, in. Ftprc which can have any expect command.

Although these features can be added inside the existing program can hook function, but can not guarantee everyone's requirements can be met. The only way to guarantee is to provide a common language. A good solution is to Tcl itself into the ftp and other programs to the middle. In fact, this has always been the original intention of Tcl. Before doing so in the absence, expect to provide a function but can achieve most do not require any rewriting of the program.

9. [Fsck]

fsck is also a lack of adequate user interface example. fsck provided little way to pre-answer some questions. You can do is to answer all the questions are "yes" or have to answer "no".

The following program segment shows how to make a script for automatic answering some questions "yes", while some of the questions answered "no". The following script before beginning the process of deriving fsck, then one of two types of questions to answer "yes", while the other question to answer "no".

for {} {1} {} {
eof break
"* UNREF FILE * CLEAR?" {Send "r"}
"* BAD INODE * FIX?" {Send "y"}
"*?" {Send "n"}

In the following version, the two questions are different. Moreover, if the script encountered something it does not understand what it will execute the command to control to the users interact. The user's keystrokes directly to the fsck process. When executed, the user can press the "+" key to exit or to control the return expect. If the control is returned to the script, the script will automatically control the operation of the rest of the process.

for {} {1} {} {
eof break
"* UNREF FILE * CLEAR?" {Send "y"}
"* BAD INODE * FIX?" {Send "y"}
"*?" {Interact +}

If you do not expect, fsck only at the expense of certain features of the circumstances can non-interactive operation. fsck is almost non-programmable, but it is the most important system management tools. Many other tools, user interface is the same deficiencies. In fact, it is less than some of the procedures which led to expect the birth.

10 [control of multiple processes: Job Control]

expect the concept of job control to avoid the usual compact implementation difficulties. Including two questions: how to handle a classic of expect job control, that is, when you press ^ Z key on the terminal when the expect to deal with; expect the other one is how to deal with multiple processes.

Processing the first question is: ignore it. expect the classical knowledge of job control. For example, you derive a program and send a ^ Z to it, it will stop (this is the perfect place pseudo-terminal) and expect it will wait forever.

But, in fact, this is simply not a problem. For an expect script, there is no need to send a process ^ Z. In other words, there is no need to stop a process. expect simply ignores a process, put their attention to other places. This is the expect job control thought, this idea has been working well.

From the user point of view is like this: When a process started by the spawn command, the variable was set to spawn_id a process descriptor. The process described by the spawn_id is considered the current process. (This descriptor is precisely the pseudo-terminal file descriptor, although users treat it as an opaque object). expect and send commands to interact only with the current process. Therefore, the switch need to do a job just to the process descriptor is assigned to spawn_id.

Here is an example to show us how to make two chess job control processes interact. After the two processes derived after a process step to be notified first move. In the following loop, each step of the action are given to another process. Which, read_move and write_move two processes for the reader to achieve. (In fact, they are very easy to achieve, but because of too long so not included here).

spawn chess; # start player one
set id1 $ spawn_id
expect "Chess"
send "first"; # force it to go first

spawn chess; # start player two
set id2 $ spawn_id
expect "Chess"

for {} {1} {} {
set spawn_id $ id1

set spawn_id $ id2

Some applications and chess programs are not the same in chess program, the two players round flow. The following script implements a bogus program. It can control a terminal so that users can log on and work properly. However, once the system is prompted for a password or user name when, expect to start down the keystrokes until the user presses the Enter key. This effectively collect the user's password and user name, but also to avoid the normal process of posing as "Incorrect password-tryagain". Moreover, if the user is connected to another host, the extra log will be recorded.

spawn tip / dev/tty17; # open connection to
set tty $ spawn_id; # tty to be spoofed

spawn login
set login $ spawn_id

log_user 0

for {} {1} {} {
set ready [select $ tty $ login]

case $ login in $ ready {
set spawn_id $ login
{"* Password *" "* login *"} {
send_user $ expect_match
set log 1
"*"; # Ignore everything else
set spawn_id $ tty;
send $ expect_match
case $ tty in $ ready {
set spawn_id $ tty
expect "* *" {
if $ log {
send_user $ expect_match
set log 0
"*" {
send_user $ expect_match
set spawn_id $ login;
send $ expect_match

This script works like this. First, the login process and connected to a terminal. By default, all conversations are recorded to standard output (by send_user). Because we are not interested, so we command "log_user 0" to disable this feature. (There are many commands to control the visible or can record something).

Inside the loop, select the login process on the terminal or waiting for the action, and returns a table waiting for input spawn_id. If you find a value inside the table, then, case on the implementation of an action. For example, if the string "login" in the output of the login process, suggesting that it will be recorded to the standard output, and a flag is set to inform the script began to record the user's keystrokes until the user presses the Enter key. No matter what is received, will be echoed to the terminal, a corresponding action in the terminal portion of the script execution.

These examples show the expect job control. By inserting himself into the conversation inside, expect the process can be created between the complex I / O streams. You can create multiple fan-out, fan-multiplexing, dynamic data related to the process diagram.

In contrast, shell makes its own time to read a file line was very difficult. shell to force users to press the Control key (for example, ^ C, ^ Z) and keywords (such as the fg and bg) to achieve the operating switch. These can not be used from inside the script. Is similar: to run non-interactively in shell does not deal with the "History" and other just for the interactive use of design features. It also appeared in the previous issue which is similar to the passwd program. Similarly, the return can not be written to test some of the action of the shell shell script. As a result the shell in these areas can not be thoroughly tested.

If you expect, you can use it to drive the interactive job control shell. A derivative of the shell that it is running in interactive, so the normal processing operation will be controlled. It can not only solve the inspection process the shell job control and other procedures. Also, when necessary, so expect to shell instead of processing operations. Can support the use of shell-style job control to support the process of running. This means: First, derive a shell, and then give the command shell to start the process. If the process is suspended, for example, sending a ^ Z, the process will stop, and returns control to the shell. To expect in terms of, a process in dealing with it (the original that shell).

expect a solution not only has great flexibility, it also avoids duplication of already present in the shell job control software. By using the shell, because you can choose you want to derive the shell, so you can get the job need to control. Moreover, once you need (for example, when testing), you can drive a shell to make this an interactive shell that it is running. This is to detect whether they are for the operation of the interactive will change the output buffer after the procedure is also very important.

To further control, during the execution of the interact, expect the control terminal (the terminal is to start expect that, instead of pseudo-terminal) is set to raw mode so that characters can be correctly transmitted to the derivation process. When interact expect in the absence of implementation, when the terminal is in cooked mode, this time the role of job control in expect itself to be.

11. [Interactive use expect]

Earlier, we mentioned that you can interact with the command to the interactive script. Basically, interact command provides free access to the dialogue, but we need some more fine-grained control. This, we can use expect to achieve, because expect to read input from standard input and read input from the process as simple. However, we want to use expect_user and send_user to the standard I / O, without changing the spawn_id.

The following script in a certain period of time to read one line from standard input inside. This script is called timed_read, which can be called from csh, for example, set answer = "timed_read 30" will be able to call it.

#! / Usr / local / bin / expect-f
set timeout [lindex $ argv 1]
expect_user "*"
send_user $ expect_match

The third line from the user to receive any newline end of any line. The last line and returns it to standard output. If a specific period of time did not receive any type, returns are also empty.

The first line of support "#!" System startup script directly. (If the script executable with the properties in the script is not adding expect). Of course, the script can always be explicit with the "expect scripot" to start. The-c option after the implementation of any statements before the script is executed. For example, do not modify the script itself, only on the command line with-c "trace ...", the script can add trace feature (The ellipsis indicates trace option).

In the command line can actually add more than one command, as long as the middle of the ";" can be separated. For example, the following command line:

expect-c "set timeout 20; spawn foo; expect"

Once you set the timeout period and the program starts, expect to wait on the start or end of file character timeout of 20 seconds. If you encounter a file character (EOF), the program will stop, and then expect to return. If you encounter a timeout, expect to return. In both the cases which are implicit to kill the current process.

If we do not expect to use examples from both of these functions, we can still learn a lot of things. In both the cases inside, the usual solution is another sleeping child process fork and signal notification with the original shell. If this process occurs first, or read the words, shell Division that will kill the sleep process. Pass the background process pid and prevent generation start information is a master class in addition to shell programmers so that people outside of headache. Provide a common way to start multiple processes like this will make a shell script is very complex. It almost certainly is that programmers generally use a dedicated C program to solve such a problem.

expect_user, send_user, send_error (terminal output to standard error) in relatively long, the process used to come from the complex interaction translated into a simple expect scripts which interact more frequently used. In reference [7] which, Libs describe how the safety of their feet have been wrapped (wrap) adb, how the system administrator from the need to know the details of which adb freed, while greatly reducing keystrokes due to an error caused by system collapse.

A simple example can make a private ftp automatically from the inside to take account files. In this case, the required password. Even if the file access is restricted, you should avoid storing passwords in clear text inside the file. The password as a parameter when the script is not appropriate, because with the ps command to see them. There is a solution that is called at the beginning expect_user script to allow users to enter a password may be used later. The password must only allow the script to know, even if you are every hour retry ftp.

Even if the information is immediately entered into, this technique is very useful. For example, you can write a script, every host on your account on a different password for all get rid of, regardless of whether they are using is not the same password database. If you want to achieve such a function by hand, you have to Telnet to each host, and manually enter a new password. The use of expect, you can just enter the password once and let the script to do other things.

expect_user and interact in a script which can also be mixed use. Consider a program in the debugging cycle, after a lot of steps before failure. Which can drive an expect script debugger, set breakpoints, execute several steps of the program cycle, then returns control to the keyboard. It can also return control before the loop and switching back and forth between the test conditions.

File ftp-down

  1. #! / Usr / bin / expect-f
  2. set ipaddress [lindex $ argv 0]
  3. set username [lindex $ argv 1]
  4. set password [lindex $ argv 2]
  5. spawn ftp $ ipaddress
  6. expect "* Name *"
  7. send "$ username \ n"
  8. expect "* Password: *"
  9. send "$ password \ n"
  10. expect "* ok * ftp> *"
  11. send "get teste \ n"
  12. expect "* ftp> *"
  13. send "quit \ n"
  14. expect eof

Copy code

Executed as follows

  1. . / Ftp-down temp temp

Copy code

The name of the FTP host address pin name user name password

  • Turn: expect the basic usage 2011-03-19

    First, an overview Shell we can achieve a simple control flow functions, such as: cycling, judgments. But you need to interact with the occasion to intervene must be artificial, and sometimes we may need to implement and interactive programs such as

  • Jpetstore study through the basic usage WSAD.ROSE.WEBSPHERE 2009-06-17

    Copyright notice: You can freely reprint, reprint, and be sure to retain the link below: Author: moyunhe Source: Product Matrix WebSphere and IBM Forum Preface <br /> Although IBM gave up WSAD, ROSE continued development (replaced by the Rational So

  • Beanutils Basic Usage [reproduced] 2010-03-29

    Beanutils Basic Usage Beanutils used the magic of reflection technology to achieve a lot of useful features exaggerated, are C / C + + did not dare think about the times. No matter who the project, and always will be the lingua franca of the day it i

  • (Transfer) window.showModalDialog the basic usage and use of skills 2009-01-28

    The basic usage window.showModalDialog showModalDialog () (IE 4 + support) showModelessDialog () (IE 5 + support) window.showModalDialog () method is used to display HTML content to create a modal dialog. window.showModelessDialog () method is used t

  • The basic usage of session and the session in tomcat to set the expiration time 2008-07-29

    1, the basic usage seesion-building: request.getSession (true); In the session to add and delete data: Method Description putValue (String, Object) set the session content removeValue (String) to delete the contents of seesion Get session variable co

  • The basic usage of git 2010-04-25

    (Edit by king) now have been using git as version management software, the original home of the Godson computers built a gitosis (build process can look at my personal blog: http://blog.sina.com.cn/s/blog_445694b90100djiu . html and http://blog.sina.

  • The basic usage command linux zip 2010-04-26

    linux zip command of the basic usage is: zip [parameters] [filename after the package] [package's directory path] linux zip command parameter list: -A conversion of documents into ASCII mode -F try to repair the damaged zip file -H Display help scree

  • JFreeChart basic usage examples (1) 2010-07-23

    JFreeChart basic usage examples (1) 1 1, JFreeChart access. JFreeChart JFreeChart is open-source Web site in a project on SourceForge.net, the company's main products are as follows: 1, JFreeReport: Report solving tools 2, JFreeChart: Java graphics s

  • Linux rpm command under the basic usage 2010-08-19

    rpm Basic Usage 1. Install a package # Rpm-ivh 2. Upgrade a package # Rpm-Uvh 3. Remove a package # Rpm-e 4. Installation Parameters - Force even if the cover package of documents belonging to others forced to install - Nodeps if the RPM package inst

  • The mysqldump tool MySQL Basic Usage 2010-09-03

    Export to MySQL use the mysqldump tool, the basic usage is: shell> mysqldump [OPTIONS] database [tables] If you are not given to any table, the database will be exported. Through the implementation of mysqldump - help, you can get your version of mys

  • Tortoise SVN Client Basic Usage 2010-09-07

    Tortoise SVN Client Basic Usage 1. Export and check out export download the source code usage: 1, create a new empty folder, right click it, you can see the TortoiseSVN menu and above the SVN Checkout. 2, do not control the Checkout, we choose Tortoi

  • The basic usage Properties 2010-12-13

    Properties Properties basic knowledge of the basic usage java.util.Properties class is used to store the key in a file - value pairs, where keys and values are separated by an equal sign, as shown in Listing 1. Listing 1. A set of attributes example

  • Custom ORM series (c) prototype tools and basic usage 2010-12-21

    Introduction This gave me the tools to introduce the prototype structure, and basic usage, but please speak up. At first glance, this sort of like NHibernate. Here, surely someone has to Paizhuan. In fact, I know. I do not inflow of this things, and

  • Turn on ibatis like usage 2011-03-02

    Turn on ibatis like usage Sql Code 1.SELECT * 2. FROM user 3. WHERE username like '%' | | # username # | | '%' SELECT * FROM user WHERE username like '%' | | # username # | | '%' In fact, the above statement is for Oracle, for different data string c

  • MySQL basic usage of mysqldump tool 2011-04-06

    Export to MySQL use the mysqldump tool, the basic usage is: shell> mysqldump [OPTIONS] database [tables] If you do not give up any table, the database will be exported. By executing mysqldump - help, you can get your version of mysqldump supports the

  • Wen Gu conceivable new - gcc and vi Basic Usage 2010-04-15

    vi editor is all standard Unix and Linux systems editor, it is not inferior to any of the latest powerful text editor, here is a brief introduction it is used and a small part of the instruction. Unix and Linux systems due to any version, vi editor i

  • Vi Editor basic usage 2011-04-12

    Original: http://xfbay.blog.51cto.com/1465928/305920 The vi editor is all Unix and Linux systems standards editor, it is not inferior to any new powerful text editor, here is a brief introduction about its usage and a small part of the instructions.

  • JavaScript Basic Usage 2009-04-29

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTEN

  • The basic usage of Chu Shi ibatis 2009-04-11

    ibatis is the internet "and" abatis "The combination is a" semi-automated "to ORM implementation. ibatis It is a lightweight framework, according to Mr Fung Man-teacher said it was the best programmers make are cut because of his

  • jquery.validate.js Introduction to the basic usage (transfer) 2010-06-21

    jquery.validate.js is a verification under jquery plugin, features more powerful, but one does not already have heard of hands used, and now is able to look up. Here is reproduced an article written by the older generation, in my own understanding of