Implementation of expect interaction free shell script

Time:2020-10-31

Expoxt overview

Expect is a tool based on TCL, and expect is a tool for automatic control and testing. It mainly solves the problem of non interaction in shell script. It is helpful for large-scale system operation and maintenance. In the daily operation and development, Yuncheng often needs to log in to the server. However, the login process is an interactive process, which may require input of yes / no and other information. The interaction free operation can be realized by using expect script.

Expect installation

Mounting CD
Make local Yum source
Execute the installation command
yum install expect -y

Basic command

send
Send a string to the process to simulate the user’s input. This command can’t automatically return the line. Generally, it needs to add a carriage return.

expect
An internal command of expect to judge whether the last output result contains the specified string. If so, it will return immediately. Otherwise, it will wait for the timeout to return. You can only capture the output of processes started by spawn.

spawn
Start the process and track subsequent interaction information

interact
After the execution is completed, the interactive state is maintained, and the control right is handed over to the console

Timeout
Specify the time-out, and continue to execute subsequent instructions after expiration
Unit: Second
Timeout – 1 is never timeout
The default timeout is 10 seconds

exp_continue
Allow expect to continue down the instruction

send_user
Echo command, equivalent to echo output of

$arvg parameter array
The expect script can accept parameters passed from bash. It can be obtained by using [lindex $arvg n], where n starts from 0 and represents the first, second, and third parameters, respectively

Expect scripts must end with interact or expect ecof, which is usually enough to perform automation tasks
Expect EOF is really waiting for the end flag. The command started by spawn generates an EOF flag at the end of the command, and expect EOF is waiting for this flag

Expect grammar

One branch grammar


expect "passwd:" {send"mypasswd\r";}

Multi branch grammar

expect"aaa"{send"AAA\r"}
expect"aaa"{send"AAA\r"}
expect"aaa"{send"AAA\r"}
//The send command does not have carriage return and line feed function. Generally, it needs to add or
expect{
"aaa"{send"AAA\r"}
"bbb"{send"BBB\r"}
"ccc"{send"CCC\r"}
}
//As long as any one is matched, execute the hard send statement and exit the expect statement
expect{
"aaa"{send"AAA";exp_continue}
"bbb"{send"BBB";exp_continue}
"ccc"{send"CCC"}
}
//exp_ Continue means to continue the following matching. If AAA is matched, BBB will be continued after the send statement is executed

-The re parameter represents the matching regular expression

Expect execution mode

1. Direct execution

Case study:
SSH login
First landing
Normal login
The connection is rejected. The SSH may not be opened, or the port number is incorrect, or the firewall is restricted
There is no such connection address

[[email protected] ~]# vim a.sh

#! / usr / bin / expect // expect binary file path
#Time out
Set timeout 20 // 20 seconds waiting time
log_ file  test.log         //Log file
log_ User 1 // log user
#Parameter input
Set hostname [lindex $argv 0] // append parameter 0, count variables and load the first position parameter
Set password [lindex $argv 1] // add parameter 1, count variables and load the second parameter
#Tracking command
Spawn SSH root @ $hostname // trace command
#Capture information and match without interactive execution
Expect {// capture prompt information
    "Connection reused" exit // when the information of rejected connection is captured, exit
    "Service not konwn" exit // if the service is opened, exit
    "(yes / no)" // capture yes or no parameters
    {send "yes\r";exp_ Continue} // enter yes and continue        
    "* password" // capture parameters  
    {send "$password / R"} // enter the password parameters       
}
#Control is handed over to the console
// input control
Exit // exit script

[ [email protected]  ~]#Chmod + X a.sh // grant script execution permission
[ [email protected]  ~]#. / a.sh 192.168.235.134 123123 // run script remote connection
spawn ssh [email protected]
[email protected]'s password: 
Last login: Thu OCT 10 15:13:27 2019 from 192.168.235.1 // remote login succeeded
[[email protected] ~]# exit          
Log out
Connection to 192.168.235.134 closed

2. Embedded execution

Case study:
Create user Jarry, password 123123

[[email protected] ~]# vim c.sh

#!/bin/bash 
user=$1
password=$2
#Non interactive commands are placed outside expect
useradd $user
#Start interacting
Expect < < - EOF // expect start flag, standard input, equivalent to stdin
spawn passwd $user
Expect "new *"
send "$password\r"
Expect "re *"
send "$password\r"
expect eof;
EOF // expect ends the statement. There must be no space before and after EOF

[[email protected] ~]# chmod +x c.sh
[[email protected] ~]# ./c.sh jarry 123123
spawn passwd jarry
Change the password of user Jarry.
New password:
Invalid password: password is less than 8 characters
重新输入New password:
Passwd: all authentication tokens have been successfully updated.

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.