/ Usr / bin / expect introduction

/ usr / bin / expect introduction
overview
and we achieve a simple flow control function by Shell, such as: cycle and judgment. But for applications that require interaction must intervene manually, sometimes we may need to implement and interactive programs such as telnet servers function interaction. And Expect to use tools to achieve this functionality.
Expect is a free programming language tool, used for automatic and interactive communication tasks without human intervention. Expect author of Don Libes time in 1990 to write Expect Expect to do the following definitions: Expect is a suite of software used to implement automatic interactive features (Expect [is a] software suite for automating interactive tools). System administrators can use it to create scripts used to implement provide input to the command or program, and these commands and programs are expected to get input from the terminal (terminal), generally you need to manually enter these inputs are carried out. Expect you can enter the prompts to provide analog standard procedure to enter the program needs to achieve an interactive program execution. It can be achieved even achieve a simple BBS chat robot.
Expect is evolving over time, which is more powerful, it has become a powerful assistant administrator of the system. Expect the need to support Tcl programming language, to run Tcl Expect must first install on your system.
Expect works
from the simplest level terms, Expect works as a generic script Chat tool. Chat script for the first UUCP network to be used to realize the need for automation of specific login session when a connection between computers.
Chat script by a series of pairs expect-send: expect to wait for the output of the output specific characters, usually a prompt, and then transmit a specific response. For example, the following script Chat wait standard output appears Login: string, and then send somebody as a user; then wait Password: prompt, and sends a response sillyme.
Login: somebody Password: sillyme
This script is used to implement a login process, and to achieve a specific log in with a user name and password.
Expect the easiest script on the operating mode of the nature and Chat Script mode of operation is the same.
example:

1, functional
we analyze a response chsh orders script below. We first look at this interactive format command. Suppose we want to change the login script for the user chavez, request command to achieve the interaction is as follows:
# the chsh chavez
Changing at The the Login shell for chavez
the Enter at The new new value, or Press return for at The default
the Login Shell [/ bin / bash]: / bin / tcsh
#
can see that the first command line prompt and output a number of prompts for the user's new login shell. We must be prompted for a user's login shell back information or directly enter does not modify the login shell.

2, the following is a script that can be used to achieve Expect automatically execute the command:
! # / Usr / bin / the Expect
# Change the Login A shell to tcsh

set user [lindex $argv 0]
spawn chsh $user
expect "]:"
send "/bin/tcsh "
expect eof
exit

This simple script can explain many features of Expect program. And other scripts designated as the first line of the script to execute command program, here is / usr / bin / expect. The first trip to the script execution parameter obtained (which is stored in the $ argv array, 0 is a parameter from the start), and save it to variable user.
The second parameter spawn Expect command to start the session commands and scripts, here is the start of the chsh command, the order is actually fertility sub-processes to run.
Subsequent expect and send command to implement interactive process. Script output wait appears]: string, once chsh output to the string appears in the output characteristics (typically feature information is the feature character string is often the last prompt waiting for input). For additional information will be completely ignored that do not match. When the script obtained feature character string, expect the transmission / bin / tcsh and a carriage order to chsh. Finally, the script waits for the command to exit (chsh end), upon receiving the identity of the child process has ended eof character, expect the script will end.

3, decide how to respond
Managers often have needs, hopes to different ways to respond to an order based on the current situation. We can expect to see examples of the latter can achieve very complex conditions respond, but only by a simple modification of pre-scripts can be achieved. The following example is a more complicated example expect-send:
Expect -Re "\ [(*.)]:"
IF {! $ Expect_out (. 1, String) = "/ bin / tcsh"} {
Send "/ bin / tcsh "}
Send" "
expect EOF
in this example, the first command now expect -re used parameters, this parameter indicates that the specified character string is a regular expression, instead of a normal string. For the above example is to find a left bracket character (which three must escape (escape), there are three symbols, because it is the expression to expect for both positive and special characters) followed by zero or more character, and finally a right square bracket character. Here. * Represents any one or more characters, which is stored in the () is stored in the matching result as a variable to achieve a subsequent access to the matching result.
When a match is found it is checked string contained in [], and see whether or / bin / tcsh. If not, then the transmitting / bin / tcsh order to chsh as input, is transmitted only if a carriage return. This simple issue different phase response of the specific situation of small examples of the power of expect.
When a regular expression may comprise a number of portions () and accessed through expect_out array. Encoding each part in the expression from left to right, starting with 1 (0 output includes the entire match). () May occur nested case, the encoding from the innermost to the outermost layer is performed in this case.

4, a timeout
next examples will expect a prompt function set forth with a timeout function. The script prompts the user if there is no input within a given period of time, it times out and returns a default response. This script takes three parameters: the prompt string, and a default response timeout time (seconds).
#! / usr / bin / the Expect
# Prompt function with timeout and default.
the SET prompt [0 lindex $ argv]
the SET DEF [1 lindex $ argv]
the SET the Response $ DEF
Tout [2 lindex $ argv] the SET
first part of the script first, operating parameters to save it to internal variables.
send_tty "$ prompt:"
SET timeout $ Tout
Expect "" {
SET RAW $ expect_out (Buffer)
# Remove Final Carriage return
SET Response [String TrimRight "RAW $" ""]
}
IF { "$ Response" == "} { the Response $ DEF} the SET
the send "the Response $"
# Prompt function with timeout and default.


the Response $ DEF the SET
the SET Tout [lindex $ argv 2]
This is the content of the rest of the script. See send_tty command to achieve the display prompt string and a colon and a space on the terminal. set timeout command sets all subsequent commands expect to wait for a response timeout $ tout (-l parameter to disable any overtime).
Then expect to wait for a carriage return character appears on the command output. If you get a carriage return before the timeout, then set the command will be assigned to the user input changing face raw. Subsequent commands entered by the user of the contents of the last carriage return after removing assigned to the variable response.
Then, if the response to the contents of space will be the response value to the default values (if the user does not enter a timeout or after a user inputs only a carriage return). Finally send an order value of a variable with the carriage response to a standard output.
An interesting thing is that the script does not use spawn command. The script will expect to interact with any process that calls the script.
If the script called prompt, it can be used in any C style shell.
SET A =% 'prompt "AN answer the Enter" Silence 10'
the Enter answer AN: Test

Answer The echo WAS% "$ A"
Answer The WAS Test
prompt timeout is set to 10 seconds. If the timeout or the user simply entered the carriage return, echo command output
Answer was "silence"

5, a more complex example
below we will discuss a more complicated script examples expect, this script uses some of the more complex control structures and many complex interaction. This example used to implement write command sent to any user, messages sent from a file or from a keyboard input.
#! / usr / bin / the Expect
# Multiple the Write to the Users from the Prepared A File
# A or the INPUT interactively the Message

if {$argc<2} {
send_user "usage: $argv0 file user1 user2 ... "
exit
}

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

set nofile 0
# get filename via the Tcl lindex function
set file [lindex $argv 0]
if {$file=="i"} {
set nofile 1
} else {
# make sure message file exists
if {[file isfile $file]!=1} {
send_user "$argv0: file $file not found. "
exit }}

This is partly achieved startup script processing parameters, which must be a stored message to be transmitted or indicates the file name "i" command importation of use of the content transmission cancellation.
File variable is set to the value of the first parameter is a script, it is achieved by the lindex a Tcl function, the function to obtain a specific element from a list / array. [] Is used to implement a function as a parameter set command lindex return value.
If the first parameter is the script lowercase "i", then the variable nofile is set to 1, otherwise to verify the parameters specified file exists by calling the function isfile Tcl, and if there is no error exit.
Here you can see if the command is determined to implement logic functions. After the command directly with the determination condition, and executes the command within the {} of the determination condition. if condition is false, the runtime block after else.
{} procs SET
# Start write Processes
for SET {I}. 1 I {$ <$ argc}
{} {I incr
spawn -noecho write
[the lindex the argv $ I $]
lappend procs $ spawn_id
}
last part using the write command to start spawn process send messages to users. As used herein, the for loop command to achieve the control function, the loop variable is first set to 1, then it increases. Loop body {} is the last content. Here we are with the second and subsequent arguments to the script to spawn a write command and each parameter name as the user to send a message. lappend internal variables using the Save command processes each spawn a process ID number $ spawn_id process of constructing a list of ID variables in procs.

if {$nofile==0} {
setmesg [open "$file" "r"]
} else {
send_user "enter message,
ending with ^D: " }

Finally, the script realize the value of a variable based on nofile open source documents or prompt the user to enter a message to be sent.
-1 timeout SET
the while. 1 {
IF {$ nofile == 0} {
IF {[mesg the gets $ chars] == -1} BREAK
SET Line "$ chars"
} {the else
expect_user {
-Re "" {}
EOF BREAK}
set line $ expect_out (buffer)}

foreach spawn_id $procs {
send $line }
sleep 1}
exit

Resources
Expect deep version of the software are many examples of the script, not only can be used to study and understand expect script, and is very used tool. Generally in / usr / doc / packages / expect / example to see them, in some linux release some expect scripts stored in / usr / bin directory.
Libes Don, the Exploring the Expect, O'Reilly & Associates, 1995.
John Ousterhout of, and the Tcl The Tk Toolkit, Addison-Wesley, 1994.
Some useful expect script
autoexpect: according to the script at runtime itself generates a user's operation expect script. Its function is somewhat analogous to the Emacs editor keyboard macro utility. Automatically create a script may be to create your own custom scripts good start.
kibitz: This is a very useful tool. Can be connected to the same shell process by which two or more users.
tkpasswd: This script provides a GUI tool to modify the user's password, you can check whether the password is included dictionary-based mode. This tool is also a good example of a learning expect and tk.

Learning Reference:
the Expect Chinese tutorial: http: //linux.sheup.com/linux/linux1240.htm

Guess you like

Origin www.cnblogs.com/alix-1988/p/12173642.html