linux--expect usage

Preface

We can implement simple control flow functions through Shell, such as looping, judgment, etc. But for situations where interaction is required, manual intervention is required, and expect is used at this time.

Example:

1. Copy the local file to the server. At this time, you will be asked to confirm and then enter the password (enter "yes" first and then enter the password), as shown below

2. When setting the jdk version, use sudo update-alternatives --config java. You need to enter the serial number to select the JDK version, as shown below

Steps for usage:

1. Install expect
        sudo apt-get install expect
2. Create a file with .sh suffix
3. Edit the file and declare at the beginning of the file to identify the type of Shell interpreter used by the script as expect:
        #! /usr/bin/expect
4. Receive When the file is executed, the command line passes parameters and defines variables:
        set jdk_command [lindex $argv 0]
        set jdk_version [lindex $argv 1]
5. Use spawn to execute the command:
        spawn sudo update-alternatives --config $jdk_command
6. The interaction starts, Check the interactive prompt line:
        expect "type selection number:"
7. Enter
        send "$jdk_version\r" in the interactive line
8. End this interaction
        expect eof

Guess you like

Origin blog.csdn.net/xch622114/article/details/131330176