Interaction-free shell script (EOF-free interaction, Expect-free interaction)

Here Document Free Interaction

  • Use I/O redirection to provide a list of commands 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.

  • Grammatical format

    命令 <<标记(EOF)
    …       (标记之间是传入的内容)
    …       
    标记(EOF)
    

Precautions

  • Marking can use any legal characters (uppercase letters) (EOF, FOE, the same before and after)
  • 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 mark. The spaces before and after the beginning mark will be omitted.

Example:

Interaction-free way to realize the statistics of the number of rows

Put the content to be counted between the tags "EOF", and pass the content directly to wc -l for statistics

wc -l <<EOF
> sheng
> mo
>  EOF
> EOF 
> EOF

Insert picture description here

Receive input and print via the read command

The input value is the part between the two EOF tags as the value of the variable i

read i <<EOF
> ni hao!
> EOF
echo $i

Insert picture description here

Set a password for the user through passwd
passwd shengmo <<EOF
> zxc123
> zxc123
> EOF

Insert picture description here

Variable substitution

When writing the file, it will first replace the variable with the actual value, and then complete the writing with the cat command

vim 1.sh
#!/bin/bash
gong="hong.txt"
name="dizu"
cat > $gong <<EOF
ni hao $name
EOF
sh 1.sh
cat hong.txt

Insert picture description here

Insert picture description here

Variable setting

Assign the whole value to the variable, and then print the variable through the echo command

vim 2.sh
#!/bin/bash
xyz="ni hao!"
di=$(cat <<EOF
this is xiaosuo
$xyz
EOF
)
echo $di
sh 2.sh

Insert picture description here

Insert picture description here

Turn off variable substitution

Output according to the original appearance of the characters, without any modification or replacement, single quotes close variable substitution, and the variables in EOF are regarded as strings

vim 2.sh

#!/bin/bash
xyz="ni hao!"
di=$(cat <<'EOF'
this is xiaosuo
$xyz
EOF
)
echo $di
sh 2.sh

Insert picture description here

Insert picture description here

Remove the TAB character before each line

Indicates that the TAB effect at the beginning of the line is inhibited

vim 2.sh

#!/bin/bash
xyz="ni hao!"
di=$(cat <<-EOF   #对标记前加“-”,即可抑制各行首TAB
    this is xiaosuo
  $xyz
EOF
)
echo "$di"
sh 2.sh

Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here

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.

  • 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.

    vim 2.sh
    
    #!/bin/bash
    xyz="ni hao!"
    : di=$(cat <<-EOF
      this is xiaosuo
    $xyz
    EOF
    )
    echo "$di"
    echo "$xyz"
    sh 2.sh
    

Insert picture description here

Expect no interaction

  • Expect is a tool based on the tcl language and is often used for automated control and testing. Mainly solve the problem of non-interaction in shell scripts, which is very helpful for large-scale Linux operation and maintenance

Expect installation

rpm -q expect
rpm -q tcl
yum install -y expect

Insert picture description here

Basic command

(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 there is, return immediately, otherwise, wait for the timeout period to 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  "$abc123\r"      #换行send部分不需要有()
方式三:
expect					#只要匹配了其中一个情况,执行相应的send语句后退出该expect语句
{
"密码1" {send "123456\r"}
"密码2"  {send "123456\r"}
"密码3"  {send "123123\r"}
}
(5) Terminator
expect eof
  • Indicates the end of the interaction, waiting for the execution to end, returning to the original user, corresponding to spawn

  • For example, when switching to the root user, the expect script waits for 10s by default. When the command is executed, it stays for 10s by default and automatically switches back to the original user.

    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, you can manually operate it. The command after interact does 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. .

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. Indicates that expect is allowed to continue to execute instructions downward.
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 follow a command such as passwd that ends the process after entering the password, 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 to be executed Report an error

(8)send_user

Represents an echo command, equivalent to echo

(9) Receive parameters

The expect script can accept the parameters passed from the bash command line and use [lindex $argv n] to get it. 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

Expect direct execution

vim 1.sh

#!/uer/bin/expect
set timeout 5
set username [lindex $argv 0]
set password [lindex $argv 1]
spawn su $username
expect "密码"
send "$password\r"
expect eof    #或者interact

Insert picture description here

Insert picture description here

Expect embedded execution

Integrate the expect process into the Shell to facilitate execution and processing

vim 4.sh

#!/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

sh 4.sh

Insert picture description here

Insert picture description here

Realize ssh automatic login

vim 5.sh

#!/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

expect 5.sh 192.168.100.128 123456

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/shengmodizu/article/details/114894314