Shell-free and interactive
- 1. Here Document is free of interaction
- Two, Expect interaction
1. Here Document is free of interaction
1. Interaction-free concept
Use I/O redirection to provide a list of commands to interactive programs or commands, such as ftp, cat, or read commands.
Is a substitute for standard input can help script developers not to use temporary files to construct input information, but directly generate a "file" on the spot and use it as standard input for "commands". Here Document can also be used with non-interactive programs and commands.
2. Grammar format
命令 <<标记
...
内容 #标记直接是传入内容
...
标记
cat > 3.txt <<EOF
> wo
> shi
> cxy
> EOF
Note: The
mark can use any legal character (usually EOF). The
ending mark must be written in the top
box, and there can be no characters in front of the ending mark. There must be no characters after the ending mark (including spaces)
. The spaces before and after the beginning mark will be omitted.
3. Related commands
①Interaction-free way to realize the statistics of the number of rows, put the content to be counted between the tags "EOF", and directly pass the content to wc -l for statistics
wc -l <<EOF
>wo
>shi
>程序员
>EOF
②Receive the input and print it through the read command. The input value is the part between the two EOF tags as the value of the variable i
read i <<EOF
>Hi
>EOF
echo $i
③Set a password for the user through passwd
passwd s5 <<EOF
>123
>123
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="EOF1.txt"
i="school"
cat > $file <<EOF
I am going to $i
EOF
cat EOF1.txt
⑤Assign the value to the variable as a whole, and then print the value of the variable through the echo command
#!/bin/bash
var="Great! I am going to home!"
i=(computer games)
myvar=$(cat <<EOF
Today is "$(date +%F)".
I can play $i.
$var.
EOF
)
echo "$myvar"
⑥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 home!"
i=(computer games)
:<<EOF
Today is "$(date +%F)".
I can play $i.
$var.
EOF
echo "12345"
Two, Expect interaction
1. Basic concepts
A tool built on the basis of the tcl language is often used for automated control and testing to solve interactive problems in shell scripts.
rpm -q expect
rpm -q tcl
yum -y install expect
Basic commands:
(1) Script interpreter
expect The file is first introduced in the script to indicate which shell is used.
#!/usr/bin/expect
(2) 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
(3) Expect
judges whether the last output result contains the specified string, and returns immediately if it has, otherwise it waits for the timeout period to return; it
can only capture the output of the process started by spawn; it is
used to receive the output after the command is executed , And then match the expected string
(4) Send
sends 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
Example:
Method 1:
expect "password" {send "abc123 \r”} #The send part of the same line must have {}
Method 2:
expect "password"
send "abc123\r" #The send part does not need to have {}
Method three:
expect supports multiple branches
expect #As long as one of the conditions is matched, exit the expect statement after executing the corresponding send statement
{ "Password 1" {send "abc123\r"} "Password 2" {send "123456\r"} "Password 3" {send "123123\r"} }
(5) The end character
expect eof
indicates the end of the interaction, waiting for the end of execution, 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 stays for 10s by default and automatically switches back to the original user.
After interact is
executed, 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. , And 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) The
default timeout time of set expect is 10 seconds. The session timeout time can be set through the set command. If the timeout time is not limited, it should be set to -1.
Example: set timeout 30
(7) exp_continue
exp_continue is appended to an expect judgment item, so that after the item is matched, it can continue to match other items in the expect judgment statement. 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
(8) send_user
send_user represents the echo command, which is equivalent to echo
(9) Receive parameters
expect The script can accept 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.
Example:
set hostname [lindex $argv 0] is equivalent to hostname=$1
set password [lindex $argv 1] is equivalent to password=$2
2. Expect to execute directly, you need to use the expect command to execute the script
①su switch user
#! /usr/bin/expect
set timeout 5 #设置超时时间
③Incoming parameters
set username [lindex $argv 0]
set password [lindex $argv 1]
④Start tracking command
spawn su $username
⑤ No interactive execution, capture information and match
expect "密码"
send "Spassword\r"
expect "*]#"
send user "ok"
⑥ Transfer control to the console
interact
expect eof
3. Embedded execution mode, integrate the expect process into the Shell, which is convenient for execution and processing
#! /bin/bash
#非交互命令放在expect外面
user=$1
password=$2
#开始免交换执行
useradd $user
#expect开始标志
/usr/bin/expect <<-EOF
#开启一个进程跟踪passwd命令,expect只能捕捉该进程信息
spawn passwd $user
expect "新的*" {send "$ {password}\r"}
expect "重新*" {send "$ {password}\r"}
expect eof
EOF
4. Realize ssh automatic login
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd [lindex $argv 1]
spawn ssh $host
expect {
#连接失败情况,比如对方ssh服务关闭
"Connection refused" exit
#找不到服务器,比如输入的IP地址不正确
"No route to host" exit
"(yes/no)" {send "yes\r" ;exp_continue}
"passwd:" {send "$passwd\r"}
}
interact
exit
5. Create disk without interaction
method one
#!/bin/bash
NEWDEV=`ls /dev/sd* | grep -o 'sd[b-z]' | uniq`
for VAR in $NEWDEV
do
echo -e "\n\np\n\n\n\nw\n" | fdisk /dev/$VAR &> /dev/null
done
mkfs.xfs /dev/${VAR}"1" &> /dev/null
Method Two
echo -e "n\np\n\n\n\nw\n" > fd.txt
disk /dev/sdb1 < fd.txt
echo "n
p
w" | fdisk /dev/sdb