Catalog title
Here Document Free Interaction
- Overview
- Use I/O redirection to provide the command list to the interactive program
- An alternative to standard input
- Grammatical format
命令 <<标记 #一般使用EOF
...
内容 #标记之间是传入内容
...
标记
Precautions for Use of Here Document
- 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
Here Document regular usage
- Interaction-free way to realize the statistics of the number of rows
EOF
, put the content towc -l
be counted between the tags , and directly pass the content to the statistics
wc -l <<EOF
>Line1
>Line2
>EOF
- Receiving a command input via read and print the input value is the two
EOF
portions between the marks, as a variablei
value
read i <<EOF
>hello #hello后面有自带的换行符有回车的功能所以$i只会获取第一行变量
>EOF
echo $i
- Set a password for the user through passwd
passwd zhangsan <<EOF
>123456 #这两行是输入的密码和确认密码
>123456
>EOF
- Support variable replacement
When writing the file, the variable will be replaced with the actual value, and then combined with the cat command to complete the writing
#!/bin/bash
file="EOF.txt"
i="substitution"
cat > $file <<EOF
Support variable $i
EOF
cat EOF.txt
- Copy the whole to the variable, and then print the variable value through the echo command
#!/bin/bash
var="Great! I am going to school!"
myvar=$(cat <<EOF
This is Line 1
Todey is Monday
$var
EOF
)
echo $myvar
- Turn off the variable replacement function, and output the characters as they are, without any modification or replacement
#!/bin/bash
var="Great! I am going to school!"
myvar=$(cat <<'EOF' #对标记加单引号或双引号,即可关闭变量替换
This is Line 1
Todey is Monday
$var
EOF
)
echo $myvar
- Remove the TAB character before each line
#!/bin/bash
var="Great! I am going to school!"
myvar=$(cat <<-EOF
This is Line 1 #在标记前加"-",即可压制各种行首TAB
Todey is Monday
$var
EOF
)
echo "$myvar"
- Multi-line comments
Bash's default comment is#
that this comment method only supports single-line comments: The introduction of Here Document solves the problem of multi-line comments, which
:
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!"
: <<-EOF
This is Line 1 .
Today is Monday .
$var
EOF
echo "abcd"
Expect basic commands
A tool built on the basis of the tcl language, often used for automated control and testing, to solve interactive problems in shell scripts
rpm -q expect
rpm -q tcl
yum install -y expect
Script interpreter
- The file is first introduced in the expect script to indicate which shell is used
#!/usr/bin/expect
spawn
- Spawn is usually followed by a Linux execution command, which means opening a session, starting a process, and tracking subsequent interaction information.
Example: spawn passwd root
expect
- Determine whether the last output result contains the specified string, if there is, return immediately, otherwise return after waiting for the timeout period; Can only capture the output of the process started by spawn;
Used to receive the output after the command is executed, and then meet the expectations String matching
send
- Send a character string to the process to simulate the user's input; this command cannot automatically enter and line feed . Generally, you must add \r (carriage return) or \n. Example:
方式一:
expect "密码" {send "abc123\r"} #同一行send部分要有{}
方式二:
expect "密码"
send "abc123\r" #换行send部分不需要有{}
方式三:
expect支持多个分支
expect #只要匹配了其中一个情况,执行相应的send语句后退出该expect语句
{
"密码1" {send "abc123\r"}
"密码2" {send "123456\r"}
"密码3" {send "123123\r"}
}
Two types of terminator
expect eof
- Indicates the end of the interaction, waiting for the execution to end, and 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 will automatically switch back to the original user after it stays for 10s by default.
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 the login is completed, 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
with interact
only a second election.
set timeout set timeout
- 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
例:set timeout 30
exp_continue continue to match
- 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 *assword 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, it will send eof to expect by default, which will cause the subsequent expect eof to be executed. Report an error
send_user
- send_user means echo command, equivalent to echo
Receive parameter set
- 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.
Example:
set hostname [lindex $argv 0] 相当于 hostname=$1
set password [lindex $argv 1] 相当于 password=$2
expect to execute directly
Need to use the expect command to execute the script
su to switch users
#!/usr/bin/expect
#设置超时时间
set timeout 5
- Parameters are passed in to
set username [lindex $argv 0]
get the first positional parameter to
set password [lindex $argv 1]
get the second positional parameter - Start tracking command
spawn su $username
call variable value - No interactive execution. After capturing information and matching
expect "密码"
su, there will be a string of passwords, and the expected string will be captured
send "$password\r"
because there is no carriage return function, so you need to add it\r
or\n
expect "*]#"
a command prompt will appear after logging in, so fill in the quotation marks *]#
send user "ok"
match Success is equivalent to echo an OK display - Give control to the console if
interact
#expect eof
you want to exit, use expect eof to exit through the set timer
Embedded execution mode
Integrate the expect process into the Shell to facilitate execution and processing
- Create user and set password
#!/bin/bash
user=$1
password=$2
- Non-interactive commands are placed outside expect
useradd $user
- Start to execute
/usr/bin/expect <<-EOF
expect without exchange. The start flag starts
spawn passwd $user
a process tracking passwd command. Expect can only capture the process information.
expect "新的*"
send "$ {password}\r" .
expect "重新*"
send "$ {password} \r"
expect eof
EOF
Realize ssh automatic login
#! /usr/bin/ expect
set timeout 5
set hostname [l index $argv 0 ]
set password [l index $argv 1]
spawn ssh $hostname
expect {
There are many possibilities for
"Connection refused" exit
connection failure. The other party's ssh service may be closed (the content prompted by different versions may be different, this is centos7), the
"Name or service not known" exit
server cannot be found, and the IP address may be entered incorrectly (the content of the prompt may be different for different versions, this is centos7)
" (yes/no)" {send "yes\r" ;exp_ continue}
If it matches the result of yes/no, it will choose yes to continue the subsequent operation. The
"password:" {send "$password\r"}
rest will only match this result, then execute this content directly. Calling
interact
the command after $password interact does not work.
exit
Create disk partitions without interaction
- Prepare a new disk
- Script content
#!/bin/bash
read -p "输入需要创建的磁盘分区" a
/usr/bin/expect <<-EOF
spawn fdisk $a
expect "命令" {send "n\r"}
expect "Select" {send "\r"}
expect "分区" {send "\r"}
expect "起始" {send "\r"}
expect "Last" {send "\r"}
expect "命令(输入 m 获取帮助):" {send "w\r"}
expect eof
EOF
partprobe
mkfs.xfs $a -f &> /dev/null
if [ $? -eq 0 ]
then
echo -e "\033[31m 磁盘格式化完成 \033[0m"
mkdir $a.1
mount $a $a.1
df -h
else
echo "格式化失败,脚本有问题"
fi
- Install expect
- Execute script
sh
orchmod +x提权再./