Secretly learn shell script free interaction (EOF free interaction, Expect free interaction)

1. Here Document is free of interaction

1. Related concepts

  • Use I/O redirection to provide the command list to interactive programs, such as ftp, cat or read commands
  • Being a substitute for standard input can help script developers not to use temporary files to construct input information, but directly produce a "file" and use it as standard input for "commands". Here Document can also be used with non-interactive programs and commands.

2. Grammar format

命令  <<标记
...	
内容			#标记之间是传入内容
...
标记

3. Matters needing attention

  • The mark can use any legal character (usually EOF)
  • The ending mark must be written in the top grid without any characters in front
  • There can be no characters (including spaces) after the ending tag
  • The spaces before and after the opening tag will be omitted

4. Example

(1) Realize the statistics of the number of rows without interaction

  • Put the content to be counted between the tags "EOF", and directly pass the content to wc -l for statistics
wc -l <<EOF
>Line1
>Line2
>EOF

Insert picture description here

(2) Receive input and print through the read command

  • The input value is the part between the two EOF tags as the value of variable i
read i <<EOF
>Hi
>EOF
echo $i

Insert picture description here

(3) Set a password for the user through passwd

passwd lisi <<EOF
>abc1234 			#这两行是输入的密码和确认密码
>abc1234
>EOF

Insert picture description here

(4) Support variable substitution

vim ti.sh
#!/bin/bash
file="ti.txt"
i="lisi"
cat > $file <<EOF
hello $i
EOF

sh ti.sh
cat ti.txt

Insert picture description here

(5) Assign a value to the variable as a whole

#!/bin/bash
var="Great! I am going to school!"
bian=$(cat <<EOF
Today is Monday.
$var
EOF
)
echo $bian

Insert picture description here

(6) Turn off the function of variable substitution

#!/bin/bash
var="Great! I am going to school!"
bian=$(cat <<'EOF'
Today is Monday.
$var
EOF
)
echo $bian

Insert picture description here

(6) Remove the TAB character before each line

#!/bin/bash
var="Great! I am going to school!"
bian=$(cat <<-EOF		#对标记前加“-”,即可抑制各行首TAB或空格			 
	Today is Monday.
  $var
EOF
)
echo "$bian"

Insert picture description here

(7) Multi-line comments

  • The default comment of Bash is "#", this comment method only supports single-line comments
  • The introduction of Here Document solves the problem of multi-line comments. ":" represents an empty command that does nothing. The content of the middle mark area will not be executed and will be ignored by bash, so the effect of batch comments can be achieved.
#!/bin/bash
var="Great! I am going to school!"
: bian=$(cat <<EOF
        Today is Monday.
  $var
EOF
)
echo "$bian"
echo "$var"

Insert picture description here

Two, Expect no interaction

  • A tool built on the basis of the tcl language, often used for automated control and testing, to solve interactive problems in shell scripts
  • Installation tool
rpm -q expect
rpm -q tcl
yum install -y expect

1. Basic commands

(1) Script interpreter

  • The file is first introduced in the expect script to indicate which shell is used.
#!/usr/bin/expect

(2)spawn

  • Spawn is usually followed by a command to open a session, start a process, and track subsequent interaction information.
例:spawn passwd root

(3)expect

  • Determine whether the specified string is included in the last output result,
    • If yes, return immediately
    • Otherwise, wait for the timeout period and return;
  • Can only capture the output of the process started by spawn;
  • Used to receive the output after the command is executed, and then match the expected string

(4)send

  • Send a character string to the process to simulate the user's input; this command cannot automatically enter and line feed, usually add \r (carriage return) or \n
例如:发送密码
方式一:
expect "密码" {
    
    send "123456\r"}		#同一行send部分要有{}
方式二:
expect "密码"	
send "123456\r"							#换行send部分不需要有{}
方式三:
expect					#只要匹配了其中一个情况,执行相应的send语句后退出该expect语句
{
    
    
"密码1" {
    
    send "123456\r"}
"密码2" {
    
    send "123123\r"}
"密码3" {
    
    send "abc123\r"}
}

(5) Terminator

  • expect eof
  • Indicates the end of the interaction, wait for the execution to end, and return to the original user, corresponding to spawn
  • For example, when switching to the root user, the expect script waits for 10s by default. After executing the command, it will automatically switch back to the original user after it stays for 10s by default.
expect eof
  • interact
  • After the execution is completed, the interactive state is maintained, and the control is transferred to the console. It will stay at the target terminal instead of returning to the original terminal. At this time, it can be operated manually. The commands after interact do not work, such as adding exit after interact. It will not exit the root user. If there is no interaction, it will log out after logging in, instead of staying on the remote terminal.
  • If you use interact, you will stay in the terminal instead of returning to the original terminal. For example, when you switch to the root user, you will always be in the root user state; for example, when you ssh to another server, you will always be in the target server terminal instead of switching back to the original server. .
interact

Note: Expect eof and interact can only choose one.

(6)set

  • The default timeout period of expect is 10 seconds. The session timeout period can be set through the set command. If the timeout period is not limited, it should be set to -1.
例:设置超时时间为30秒
set timeout 30

(7)exp_continue

  • exp_continue is appended to a certain expect judgment item, so that after the item is matched, it can continue to match other items in the expect judgment sentence. exp_continue is similar to the continue statement in the control statement.
  • For example: The following example will determine whether there is yes/no or *password in the interactive output. If it matches yes/no, output yes and execute the judgment again; if it matches *password, output abc123 and end the expect statement.
expect {
    
    
    "(yes/no)" {
    
    send "yes\r"; exp_continue;}
    "*password" {
    
    set timeout 300; send "abc123\r";}
}

Note: When using exp_continue, if you track commands that terminate the process after entering a password like passwd, do not add expect eof outside of expect{}
because after the spawn process ends, eof will be sent to expect, which will cause the subsequent expect eof execution to report an error

(8)send_user

  • Represents an echo command, equivalent to echo
send_user

(9) Receive parameters

  • The expect script can accept parameters passed from the bash command line and get it using [lindex $argv n]. Among them, n starts from 0 and represents the first, second, third...parameters respectively.
例:
set hostname [lindex $argv 0]   	相当于 hostname=$1
set password [lindex $argv 1]		相当于 password=$2

2. Example

(1) Expect direct execution

  • Execution cannot be executed in the previous way, you need to use the expect command to execute the script
  • Example: su switch user
#!/usr/bin/expect
set timeout 3
set username [lindex $argv 0]
set password [lindex $argv 1]
spawn su $username
expect "密码" {
    
    send "$password\r"}
interact         #或者expect eof

Insert picture description here

(2) Embedded execution

  • Integrate the expect process into the Shell to facilitate execution and processing
  • Example: Create a user and set a password
#!/bin/bash
user=$1
password=$2
useradd $user
/usr/bin/expect <<EOF
spawn passwd $user
expect "新的*" {send "${password}\r"}
expect "重新*" {send "${password}\r"}
expect eof                              
EOF

Insert picture description here

(3) Realize ssh automatic login

  • Execute directly with expect
#!/usr/bin/expect
set timeout 5
set hostname [lindex $argv 0]
set password [lindex $argv 1]

spawn ssh $hostname
expect {
    
    
  "Connection refused" exit
  "Name or service not known" exit
  "to continue" {
    
    send "yes\r";exp_continue}
  "password:" {
    
    send "$password\r"}
}

interact
exit			#interact后的命令不起作用

Insert picture description here

  • Embedded
#!/bin/bash
hostname=$1
password=$2
/usr/bin/expect <<EOF
spawn ssh $hostname
expect {
"(yes/no)" {send "yes\r";exp_continue}
"*password" {send "$password\r"}
}
expect "*]#" {send "ifconfig\r"}
expect eof
EOF

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51326240/article/details/111767040