Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How expect handles htpasswd interaction

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how expect handles htpasswd interaction. I hope you will get something after reading this article. Let's discuss it together.

Vim expect_test.sh

#! / usr/bin/expect

Set htpasswdpath [lindex $argv 0]

Set username [lindex $argv 1]

Set userpass [lindex $argv 2]

# spawn the htpasswd command process

Spawn htpasswd-c $htpasswdpath $username

# Automate the 'New password' Procedure

Expect "New password:"

Send "$userpass\ r"

Expect "Re-type new password:"

Send "$userpass\ r"

Expect eof

Chmod + x expect_test.sh

. / expect_test.sh / usr/local/nagios/etc/htpasswd.users (this is $argv 0) nagiosadmin (this is $argv 1) 123.com (this is $argv 2)

Expect tutorial Chinese version

Source: ChinaUnix blog date: 2007.02.14 10:58 (a total of comments) I want to comment

Expect tutorial Chinese version

Creation time: 2001-04-29

Article attribute: reprint

Article Source: BBS Station of University of Science and Technology of China

[copyright notice]

Copyright (c) 1999

This tutorial is translated by * cucurbit * with appropriate modifications and can be freely used for non-commercial purposes.

However, you must copy this [copyright notice] when you Redistribution.

[BUG]

There are many parts that cannot be "faithful and faithful" in translation. Of course, "elegance" has not been achieved at any time. I hope you will understand.

[original]

Don Libes: National Institute of Standards and Technology

Libes@cme.nist.gov

[catalogue]

1. Abstract

two。 Keyword

3. Brief introduction

Summary of 4.Expect

5.callback

6.passwd and consistency check

7.rogue and pseudo terminal

8.ftp

9.fsck

10. Multi-process control: job control

11. Interactive use of Expect

twelve。 Interactive Expect programming

13. Control of non-interactive programs

The speed of 14.Expect

15. Security considerations

16.Expect resources

17. Reference books

1. [abstract]

Modern Shell provides minimal control over the program (start, stop, etc.), while leaving interactive features to the user. This means that some programs, such as passwd, you can't run non-interactively. There are some programs that can run non-interactively, but lose flexibility to a large extent, such as fsck. This indicates that the tool construction logic of Unix is beginning to have problems. Expect fills some of these cracks and solves some of the long-standing problems in the Unix environment.

Expect uses Tcl as the language core. Not only that, Expect can be used regardless of whether the program is interactive or non-interactive. This is a classic example of a small language that works with other Unix tools to produce powerful features.

This part of the tutorial is not about the implementation of Expect, but about the use of the Expect language itself, which is mainly reflected through different script description examples. Several of these examples also illustrate several new features of Expect.

two。 [keywords]

Expect, interaction, POSIX, programmed conversation, Shell,Tcl,Unix

3. [introduction]

A Unix file system checker called fsck can be executed from within Shell with the-y or-n options. In manual [1], the-y option is defined like this.

"assume a 'yes' response for all problems with fsck; special care must be taken when using this, as it actually allows the program to continue running unconditionally, even if some very serious errors are encountered."

By contrast, the-n option is much safer, but it's actually almost useless. This interface is very bad, but there are a lot of programs in this style. The file transfer program ftp has an option to disable interactive questioning so that it can be run from a script. But once an error occurs, it does not provide a solution.

Expect is a tool for controlling interactive programs. He solved the problem of fsck and implemented all the interactive functions in a non-interactive way. Expect is not specifically designed for fsck, it can also handle errors similar to ftp.

The problems with fsck and ftp show us the limitations of user interfaces like those provided by sh,csh and other shell. Shell does not provide the ability to read from a program and write like a program. This means that shell can run fsck but only at the expense of some of the flexibility of fsck. There are some programs that cannot be executed at all. For example, if you don't have a user to provide input interactively, you can't run it. There are other programs such as Telnet,crypt,su,rlogin that cannot be executed automatically in shell scripts. There are many other applications that are designed to require user input.

Expect is designed to interact with interactive programs. An Expect programmer can write a script to describe the conversation between the program and the user. Expect programs can then run "interactive" programs non-interactively. Writing scripts for interactive programs is as simple as writing scripts for non-interactive programs. Expect can also be used to automate part of the conversation because the control of the program can be switched between the keyboard and the script.

There is a detailed description in bes [2]. To put it simply, the script is written in an explanatory language. (C and C++ 's Expect libraries are also available, but this is beyond the scope of this article.) Expect provides commands to create interactive processes and read and write their inputs and outputs. Expect is named after a command of the same name.

The Expect language is based on Tcl. Tcl is actually a subroutine library that can be embedded in a program to provide language services. The final language is a bit like a typical Shell language. There are set commands to assign values to variables, if,for,continue commands to control the execution of the program, and ordinary mathematical and string operations. Of course, you can also use exec to call the Unix program. All of these functions are available in Tcl. Tcl is described in detail in the reference book Outerhour [3] [4].

Expect is created on top of Tcl, and it also provides commands that Tcl does not have. The spawn command activates a Unix program to run interactively. The send command sends a string to the process. The expect command waits for some string of the process. Expect supports regular expressions and can wait for multiple strings at the same time, and perform different operations on each string. Expect also understands some special situations, such as timeouts and encounters at the end of the file.

The style of the expect command is very similar to that of Tcl's case command. One string is used to match multiple strings. Whenever possible, new commands are always similar to existing Tcl commands to keep the language inherited from the tool family. The following definition of expect is excerpted from the manual [5].

Expect patlist1 action1 patlist2 action2.

This command waits until the output of the current process matches one of the above patterns, or until the time exceeds a specific length of time, or until the end of the file is encountered.

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

Each patlist consists of a schema or a lists of schemas. If a pattern match succeeds, the corresponding action is executed. The result of the execution is returned from the expect.

Strings that are precisely matched (or strings that have been read but not matched when a timeout occurs) are stored in the variable expect_match. If patlist is eof or timeout, the corresponding action is not executed until the end of the file or timeout occurs. The general timeout value is 10 seconds, but you can set the timeout value to 30 seconds with commands such as "set timeout 30".

The following program segment is extracted from a script about login. Abort is a procedure defined elsewhere in the script, while other action uses Tcl primitives similar to the C language.

Expect "* welcome*" break

"* busy*" {print busy;continue}

"* failed*" abort

Timeout abort

Patterns are regular expressions in the usual C Shell style. The pattern must match the ubiquity of all the output of the current process from the previous expect or interact (so the wildcard * is used very much). However, once the output exceeds 2000 bytes, the preceding characters are forgotten, which can be changed by setting the value of match_max.

The expect command does reflect the best and worst nature of the expect language. In particular, the flexibility of expect commands comes at the expense of often confusing syntax. Apart from keyword schemas (such as eof,timeout), those schema tables can include multiple schemas. This guarantee provides a way to distinguish them. But separating these tables requires additional scanning, which may treat and as blank characters if they are not properly enclosed in ["]. The situation gets worse because Tcl provides two methods for string references: single reference and double reference. In Tcl, there is no need to use quotation marks if there is no ambiguity. There is also a separate section in the expect manual to explain this complexity. Fortunately, there are some good examples that seem to stop this complaint. However, this complexity is likely to reappear in future versions. To enhance readability, the scripts provided in this article assume that double quotes are sufficient.

Characters can be referenced separately using a backslash, which is also used to continue the statement, which ends at the end of the line without a backslash. This is also consistent with Tcl. Tcl continues to scan when it finds open single quotes or open double quotes. Also, semicolons can be used to split multiple statements in one line. This sounds a little confusing at first, but it's the style of an interpretive language, but it's really a less beautiful part of Tcl.

5. [callback]

It is very surprising how some small scripts produce some useful features. The following is a script for dialing a phone number. He uses it to reverse the charge so that long-distance calls are billed to the computer. This script is activated with something like "expect callback.exp 12016442332". Where 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 [index $argv 1]"

# modem takes a while to connect

Set timeout 60

Expect "* CONNECT*"

The first line is a comment, and the second line shows how to call a Unix program that has no interaction. Sleep 4 blocks the program for 4 seconds to give the user time to exit, because modem always calls back the phone number that the user has already used.

The following line uses the spawn command to activate the tip program so that the output of the tip can be read by the expect and the tip can read the input from the send. Once tip says it's connected, modem will ask to call Big Brother's phone number. (it is assumed that modem is he-compatible, but this script can be easily modified to accommodate other types of modem). No matter what happens, expect will stop. If the call fails, the expect script can be designed to retry, but not here. If the call is successful, getty detects DTR after expect exits and prompts the user to loging:. Practical scripts tend to provide more error detection.

This script shows the use of command-line arguments, which are stored in a table called argv (much like the style of C language). In this case, the first element is the phone number. Square brackets cause the enclosed part to be executed as a command, and as a result, the enclosed part is replaced. This is also very similar to the style of C Shell.

This script is similar to the function implemented by a C language program of about 60K.

6. [passwd and consistency check]

Earlier, we mentioned that passwd programs cannot be run without user interaction, and passwd ignores Icano redirects and cannot be embedded in pipes so that input can be read from other programs or files. This program insists on actually interacting with the user. Passwd is designed to be like this for security reasons, but as a result there is no non-interactive way to verify passwd. It is ironic that such a program that is vital to system security cannot be reliably tested.

Passwd takes a user name as a parameter and interactively prompts for a password. The following expect script takes a user name and password as parameters rather than interactively.

Spawn oasswd [index $argv 1]

Set password [index $argv 2]

Expect "* password:"

Send "$password"

Expect "* password:"

Send "$password"

Expect eof

The first line starts the passwd program with a user name as an argument, and for convenience, the second line stores the password in a variable. Like shell, the use of variables does not need to be declared in advance.

On the third line, the expect search pattern "* password:", where * allows any input to be matched, is very effective in avoiding specifying all the details. There is no action in the above program, so expect detects the mode and continues to run.

Once prompted, the next line sends the password to the current process. Indicates that enter. (in fact, all C conventions about characters are supported). There are two expect- send sequences in the above program, because passwd requires two inputs in order to confirm the input. In non-interactive programs, this is unnecessary, but our script does so because it assumes that passwd is interacting with the user.

Finally, the purpose of the line "expect eof" is to search for the file Terminator in the output of passwd, which also shows the matching of keywords. Another keyword match is timeout, where timeout is used to indicate that all matches fail to match a specific length of time. Eof is necessary here because passwd is designed to check that all of its Imax Os are successful, including the last new line generated the second time the password is entered.

This script is enough to demonstrate the basic interactivity of passwd commands. Another more complete example will examine some other behaviors. For example, the following script examines several other aspects of the passwd program. All the tips have been checked. The inspection of garbage input has also been dealt with properly. Process death, unusually slow response, or other unexpected behavior are all dealt with.

Spawn passwd [index $argv 1]

Expect eof {exit 1}

Timeout {exit 2}

"* No such user.*" {exit 3}

"* New password:"

Send "[index $argv 2"

Expect eof {exit 4}

Timeout {exit 2}

"* Password too long*" {exit 5}

"* Password too short*" {exit 5}

"* Retype ew password:"

Send "[index $argv 3]"

Expect timeout {exit 2}

"* Mismatch*" {exit 6}

"* Password unchanged*" {exit 7}

"

Expect timeout {exit 2}

"*" {exit 6}

Eof

When the script exits, it uses a number to indicate what happened. 0 indicates that the passwd program is running normally, 1 indicates unexpected death, 2 indicates locking, and so on. Numbers are used for simplicity. Expect returns a string as easily as a number, even the messages generated by the derived program itself. In fact, it is typical to store the entire interaction in a file and delete the file only if the program runs as expected. Otherwise, the log will be left for further inspection.

This passwd check script is designed to be driven by another script. This second script reads the parameters and expected results from a file. For each set of input parameters, it invokes the first script and compares the result to the expected result. Because this task is non-interactive, a plain old shell can be used to interpret the second script. For example, a passwd data file is likely to look like the following.

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 name of the first domain is the regression script to be run. The second field is the exit value that needs to match the result. The third domain is the user name. The fourth and fifth fields are the passwords that should be entered when prompted. The minus sign simply indicates that there is a domain that will never be used. In the first line, bogus indicates that the user name is illegal, so passwd responds that there is no such user. When expect exits, it returns 3. 3, which happens to be the second field. In the last line, ^ C is actually sent to the program to verify that the program exited properly.

In this way, expect can be used to verify and debug interactive software, which is exactly what IEEE's POSIX 1003.2 (shell and tools) conformance checking requires. For further explanation, please refer to Libes [6].

7. [rogue and pseudo terminal]

Unix users must be familiar with ways to connect with other processes through pipes (for example, a shell pipeline). Expect uses pseudo-terminals to associate with derived processes. Pseudo-terminals provide terminal semantics so that programs think they are performing Icano operations with real terminals.

For example, BSD's adventure game rogue runs in health mode and assumes an addressable character terminal at the other end of the connection. You can program in expect so that the game can be played by using the user interface.

Rogue this adventure game first provides you with a character with various physical attributes, such as strength values. Most of the time, the strength value is 16, but almost every 20 times there is a force value of 18. Many rogue players know this, but no one wants to start the program 20 times to get a good configuration. The following script will do just that.

For {} {1} {} {

Spawn rogue

Expect "* Str:18*" break

"* Str:16*"

Close

Wait

}

Interact

The first line is a for loop, much like the control format of the C language. After rogue starts, expect checks to see if the force value is 18 or 16. If it is 16, the program exits by executing close and wait. The purpose of these two commands is to close the connection of the pseudo terminal and wait for the process to exit. When rogue reads a file Terminator, it is launched, and the loop continues to run, generating a new rogue game to check.

When a configuration with a value of 18 is found, the control pushes out the loop and jumps to the last line of the script. Interact transfers control to users so that they can play this particular game.

Imagine running this script. All you can really see is 20 or 30 initial configurations skimming across the screen in less than a second, leaving you with a well-configured game. The only better way to do this is to use debugging tools to play games.

It is important to realize that rogue is a graphics game that uses cursors. Expect programmers must understand that the movement of the cursor is not necessarily reflected on the screen in an intuitive way. Fortunately, in our case, this is not a problem. Future improvements to expect may include an embedded terminal simulator that supports character graphics areas.

8. [ftp]

We used expect to write the first script and did not print out "Hello,World". In fact, it implements some more useful functions. It can run ftp non-interactively. Ftp is a program used to transfer files on a network that supports TCP/IP. Except for some simple functions, the general implementation requires the participation of users.

The following script fetches a file from a host using anonymous ftp. Where the host name is the first parameter. The file name is the second parameter.

Spawn ftp [index $argv 1]

Expect "* Name*"

Send "anonymous"

Expect "* Password:*"

Send [exec whoami]

Expect "* ok*ftp > *"

Send "get [index $argv 2]"

Expect "* ftp > *"

The above program is designed to ftp in the background. Although they use mechanisms similar to expect at the underlying level, their programmability needs to be improved. Because expect provides a high-level language, you can modify it to meet your specific needs. For example, you can add the following features:

Hold on-- if the connection or transmission fails, you can do it every minute or every hour, even

So that it can be carried out irregularly according to other factors, such as the user's load.

Try again.

: notification-you can be notified through mail,write or other programs during transmission, or even

Failure can be notified.

Initialization-each user can have their own initialization file written in a high-level language

(for example, .ftprc). This is very similar to the use of .cshrc by C shell.

Expect can also perform other more complex tasks. For example, he can use the Archie system of McGill University. Archie is an anonymous Telnet service that provides access to databases that describe files on the Internet that are available through anonymous ftp. By using this service, the script can ask Archie for the location of a particular file and remove it from the ftp server. The implementation of this function only requires adding a few lines to the script above.

There is no known backend yet-ftp can implement several of the above functions, let alone all of them. In expect, its implementation is very simple. The implementation of "persistence" only requires a loop in the expect script. The implementation of "notification" only needs to execute mail and write. The implementation of "initialization file" can use a command, source. Ftprc, you can have any expect command in .ftprc.

Although these features can be achieved by adding hook functions to existing programs, this does not guarantee that everyone's requirements can be met. The only way to provide assurance is to provide a common language. A good solution is to integrate Tcl itself into ftp and other programs. In fact, this is the original intention of Tcl. Before doing so, expect provides a solution that does most of the functionality without any rewriting.

9. [fsck]

Fsck is another example of a lack of adequate user interfaces. Fsck offers few ways to answer questions in advance. All you can do is answer "yes" or "no" to all the questions.

The following program segment shows how a script can automatically answer "yes" to some questions and "no" to some questions. The following script starts by spawning the fsck process, then answers "yes" to two of these types of questions, and answers "no" to the others.

For {} {1} {} {

Expect

Eof break

"* UNREF FILE*CLEAR?" {send "r"}

"* BAD INODE*FIX?" {send "y"}

"*?" {send "n"}

}

In the following version, the answers to the two questions are different. Also, if the script encounters something it doesn't understand, it executes the interact command to give control to the user. The keystroke of the user is directly handed over to fsck for processing. When the execution is finished, the user can exit or return control to expect by pressing the "+" key. If the control is returned to the script, the script automatically controls the operation of the rest of the process.

For {} {1} {} {

Expect

Eof break

"* UNREF FILE*CLEAR?" {send "y"}

"* BAD INODE*FIX?" {send "y"}

"*?" {interact +}

}

Without expect,fsck, it can run non-interactively only at the expense of certain functions. Fsck is almost unprogrammable, but it is the most important tool for system management. The user interfaces of many other tools are equally inadequate. In fact, it is the deficiency of some of these programs that led to the birth of expect.

10. [control multiple processes: job control]

Expect's concept of job control ingeniously avoids the usual difficulties in implementation. There are two questions: one is how expect handles the classic job control, that is, what expect does when you press the ^ Z key on the terminal, and the other is how expect handles multiple processes.

The solution to the first problem is to ignore it. Expect knows nothing about classic job control. For example, if you derive a program and send it a ^ Z, it will stop (this is the perfection of the pseudo terminal) and expect will wait forever.

But, in fact, this is not a problem at all. For an expect script, it is not necessary to send ^ Z to the process. In other words, there is no need to stop a process. Expect simply ignores one process and turns its attention to something else. This is expect's idea of job control, which has been working well.

From the user's point of view, it looks like this: when a process is started with the spawn command, the variable spawn_id is set to the descriptor of a process. The process described by spawn_id is considered the current process. This descriptor is precisely the descriptor of the pseudo terminal file, although the user treats it as an opaque object. The expect and send commands interact only with the current process. So all you need to do to switch a job is to assign the process descriptor to spawn_id.

Here is an example of how to make two chess processes interact with each other through job control. After two processes are derived, one process is told to take the first step. In the following loop, each step is sent to another process. Among them, read_move and write_move are left to the reader to implement. In fact, they are very easy to implement, but they are not included here because they are too long.

Spawn chess; # start player one

Set id1 $spawn_id

Expect "Chess"

Send "first"; # force it to go first

Read_move

Spawn chess; # start player two

Set id2 $spawn_id

Expect "Chess"

For {} {1} {} {

Send_move

Read_move

Set spawn_id $id1

Send_move

Read_move

Set spawn_id $id2

}

There are some apps that are quite different from chess programs, where two players flow around in chess programs. The following script implements an impersonation program. It can control a terminal so that the user can log in and work properly. However, once the system prompts for a password or user name, expect starts writing down keystrokes until the user presses enter. This effectively collects the user's password and user name, and avoids the "Incorrect password-tryagain" of the common impersonation program. Moreover, if the user connects to another host, those additional logins will also 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

Expect

{"* 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 connect to a login process and terminal. By default, all conversations are recorded on standard output (via send_user). Because we are not interested in this, we disable this feature by calling "log_user 0". There are many commands to control what can be seen or recorded.

Inside the loop, the select waits for an action on the terminal or login process and returns a spawn_ id table waiting for input. If a value is found in the table, case executes an action. For example, if the string "login" appears in the output of the login process, the prompt is recorded on the standard output, and a flag is set to tell the script to start recording the user's keystrokes until the user presses enter. No matter what is received, it will be echoed to the terminal, and a corresponding action will be executed at the terminal of the script.

These examples show how expect controls its jobs. By inserting itself into the conversation, expect can create a complex Icano stream between processes. You can create multi-fan-out, multi-fan-in, dynamic data-related process diagrams.

By contrast, shell makes it difficult to read one file at a time. Shell forces users to press control keys (such as ^ C, ^ Z) and keywords (such as fg and bg) to switch jobs. None of this can be used from the script. Similarly, shell, which runs non-interactively, does not deal with "history" and other features that are only designed for interactive use. This also has a similar problem with the previous passwd program. Similarly, it is not possible to write shell scripts that can regressively test some of the actions of shell. As a result, these aspects of shell cannot be thoroughly tested.

If you use expect, you can use its interactive job control to drive shell. A derived shell thinks that it is running interactively, so it handles job control normally. It can not only solve the problem of shell and other programs controlled by inspection and processing jobs. You can also have shell handle jobs instead of expect when necessary. You can support the use of shell-style job control to support the running of processes. This means that you first derive a shell and then send the command to shell to start the process. If the process is suspended, for example, if a ^ Z is sent, the process stops and returns control to shell. For expect, it is still working on the same process (the original shell).

The solution of expect not only has great flexibility, but also avoids repeating the job control software that already exists in shell. By using shell, since you can choose the shell you want to derive, you can gain control of the job as needed. And, once you need it (for example, when checking), you can drive a shell to make the shell think it is running interactively. This is also important for programs that change the output buffer after detecting whether they are running interactively.

For further control, during the execution of the interact, expect sets the control terminal (the terminal that starts the expect, not the pseudo terminal) into generation mode so that characters can be correctly transmitted to the derived process. When the expect does not execute the interact, the terminal is in mature mode, and the job control can act on the expect itself.

11. [interactive use of expect]

Earlier, we mentioned that scripts can be used interactively through the interact command. Basically, the interact command provides free access to the conversation, but we need some finer control. We can also use expect to achieve this, because expect reading input from standard input is as simple as reading input from a process. However, we are going to use expect_user and send_user to do the standard Imax O without changing the spawn_id.

The following script reads a line from standard input for a certain amount of time. This script is called timed_read and can be called from within csh, for example, set answer= "timed_read 30" can call it.

#! / usr/local/bin/expect-f

Set timeout [index $argv 1]

Expect_user "*"

Send_user $expect_match

The third line receives any line that ends with a new line character from the user. The last line returns it to standard output. If you do not get any typing within a specific time, the return is also empty.

The first line supports "#!" The system directly starts the script. (do not add expect in front of the script if you add executable attributes to the script.) Of course, scripts can always be started explicitly with "expect scripot". The option after-c is executed before any script statement is executed. For example, instead of modifying the script itself, just add-c "trace..." to the command line, and the script can add trace functionality (the ellipsis indicates the option for trace).

You can actually add multiple commands to the command line, as long as they are separated by ";". For example, the following command line:

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

Once you have set the timeout and the program starts, expect starts waiting for the file Terminator or a 20-second timeout. If the file Terminator (EOF) is encountered, the program stops and expect returns. If a timeout is encountered, expect returns. In both cases, the current process is implicitly killed.

If we don't use expect to implement the functions of the above two examples, we can still learn a lot. In both cases, the usual solution is to fork another sleeping child process and notify the original shell with signal. If this process or reading happens first, shell will kill the sleep process. Passing pid and preventing background processes from generating startup messages is a headache for people other than skilled shell programmers. Providing a general way to start multiple processes like this can make shell scripts very complex. So it is almost certain that programmers generally use a special C program to solve such a problem.

Expect_user,send_user,send_error (output to standard error terminals) is frequently used in long expect scripts that translate complex interactions from processes into simple interactions. In reference [7], Libs describes how to use scripts to safely wrap adb, how to free system administrators from the details that need to be mastered in adb, and greatly reduce system crashes caused by incorrect keystrokes.

A simple example allows ftp to automatically retrieve files from a private account. In this case, a password is required. Even if access to the file is restricted, you should avoid storing the password in the file in clear text. It is also inappropriate to use passwords as parameters when the script is run, because you can see them with the ps command. One solution is to call expect_user at the beginning of the script to let the user enter a password that may be used later. This password must only be known to the script, even if you have to retry ftp every hour.

This technique is very useful even if the information is entered immediately. For example, you can write a script that changes the passwords on different accounts on each host, regardless of whether they are using the same password database or not. If you want to achieve such a function manually, you must Telnet to each host and enter the new password manually. With expect, you can enter the password only once and let the script do something else.

Expect_user and interact can also be mixed in a script. Consider that when debugging a program's loop, it takes many steps before it fails. An expect script can drive which debugger, set the breakpoint, execute several steps of the program loop, and then return control to the keyboard. It can also switch back and forth between the loop body and the conditional test before returning to control. After reading this article, I believe you have a certain understanding of "how expect handles htpasswd interaction". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report