Shell Here Document Free interactive commands and Expect

One, Here Document free interactive commands

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.

语法格式:
命令 <<标记
...
内容    #标记直接是传入内容
...
标记

Precautions:
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
before the ending mark. There can be no characters after the ending mark (including spaces) . The spaces before and after the beginning mark will be omitted.

1.免交互方式实现对行数的统计,将要统计的内容置于标记“EOF”之间,直接将内容传给wc -l 来统计
wc -l <<EOF
>Line1
>Line2
>EOF

Insert picture description here

通过read 命令接收输入并打印,输入值是两个EOF标记之间的部分,作为变量i的值

read i <<EOF
>Hi
>EOF
echo $i

Insert picture description here

通过passwd给用户设置密码

passwd zhangsan <<EOF
>35123512            
>35123512
EOF

Insert picture description here

支持变量替换
在写入文件时会先将变量替换成实际值,再结合cat 命令完成写入

#!/bin/bash
file="eof1.txt"
i="school"
cat > $file <<EOF
I am going to $i
EOF

Insert picture description here
Insert picture description here

整体赋值给变量,然后通过echo命令将变量值打印出来

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

Insert picture description here
Insert picture description here

关闭变量替换的功能,按照字符原本的样子输出,不做任何修改或替换

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

echo $myvar

Insert picture description here
Insert picture description here

去掉每行之前的TAB字符

#!/bin/bash
var="Great! I am going to school!"
myvar=$(cat <<-'EOF'        #在标记前加“-”,即可抑制各行tab字符
       This is Line 1.
       Today is Monay.
       $var
EOF
)
echo "$myvar"

Insert picture description here
Insert picture description here

多行注释
Bash 的默认注释是“#”,该注释方法只支持单行注释:Here Document 的引入解决了多行注释的问题。
":"代表什么都不做的空命令。中间标记区域的内容不会被执行,会被bash忽略掉,因此可达到批量注释的效果。

#!/bin/bash
var="Great! I am going to school!"
: <<-EOF      
			This is Line1.
		Today is Monday.
	$var
EOF
echo "abcd"

Insert picture description here
Insert picture description here

Two, Expect

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

1. Basic commands

1. The script interpreter
expects the script to introduce the file first, indicating 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.

例:
spawn passwd root

3.expect
judges whether the last input result contains the specified string, if there is, return immediately, otherwise, wait for the timeout period to return: only the output of the process started by spawn can be captured; it is
used to receive the output after the command is executed, 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 wrap. Generally add \r (carriage return) or \n

方式一:
expect “密码” {
    
    send “abc123\r”}   #同一行send部分要由{
    
    }
方式二:
expect “密码”
send “$abc123\r”         #换行send部分不需要有{
    
    }
方式三:
expect “支持多个分支
expect  {
    
                         #只要匹配了其中一个情况,执行相应的send语句后退出该expect语句
"密码1 {send "abc123\r"}"
"密码2 {send "123123\r"}"
"密码3 {send "123123\r"}"
}

5. The end character
expect eof
indicates the end of the interaction, wait for the execution to end, and return to the original user. Corresponding to the spawn,
such as switching to the root user, the expect script waits for 10s by default. When the command is executed, the default stays for 10s and automatically switches back. 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. At this time, it can be operated manually. The commands after interact do not work. For example, interact will remain in the terminal instead of returning to the original. The terminal, such as switching to the root user, will always be in the root user state; for example, when ssh to another server, it will always be at the target server terminal instead of switching back to the original server.

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.

例: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 statement. exp_continue is similar to the continue statement in the control statement. Indicates that expect continues to execute instructions downward

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 *assword, 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 a password, do not add expect eof outside of expect{}
because after the spawn process ends, eof will be sent to expect by default, which will cause the expect later eof execution error

8. send_ user
send_ user represents the echo command, which is equivalent to echo

9. Receive parameters The
expect 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.

:
set hostname [lindex $argv 0]    相当于hostname=$1
set password [lindex $argv 1]    相当于password=$2

2. Example

expect直接执行,需要使用expect 命令去执行脚本
su切换用户
#! /usr/bin/expect
#设置超时时间
set timeout 5
#参数传入
set username [lindex $argv 0]
set password
[lindex $argv 1]
#开始追踪命令
spawn su $username
#免交互执行,捕捉信息并匹配
expect "密码"
send "password\r"
expect "*]#"
send user "ok" .
#把控制权交给控制台
interact
#expect eof

Insert picture description here
Insert picture description here

3. Embedded execution mode

Create user and set password

#! /bin/bash
user=$1
password=$2
#非交互命令放在expect外面
useradd $user
#开始免交换执行
/usr/bin/expect <<-EOF
#expect开始标志
spawn passwd $user
#开启-一个进程跟踪passwd命令,expect只能捕捉该进程信息
expect "新的*"
send "$ {password}\r" .
expect "重新*"
send "$ {password} \r"
expect eof
EOF

4. Realize ssh automatic login

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

spawn ssh $hostname
expect {
    
    
	"Connection refused" exit           #连接失败情况,比如对方ssh服务关闭
	"Name or service not known" exit    #找不到服务器,比如输入的IP地址不正确
	" (yes/no)" {
    
    send "yes\r" ;exp_continue}
	"password:" {
    
    send "$password\r"}
interact
exit            #interact后的命令不起作用

Embedded:

#!/bin/bash
hostname=$1
password=$2


/usr/bin/expect <<EOF
spawn ssh root@${
    
    hostname}

expect {
    
    
       "Connection refused" exit
       "No route to host" exit
       "(yes/no)" {
    
    send "yes\r";exp_continue}
       "password" {
    
    send "$password\r"}
}
expect "*]#"
send "ifconfig\r"
expect eof
EOF

5. Create disk without interaction

#!/bin/bash
disk=$1
/usr/bin/expect <<EOF
spawn fdisk $disk
expect "命令" {
    
    send "n\r"}
expect "Select" {
    
    send "p\r"}
expect "分区" {
    
    send "\r"}
expect "起始" {
    
    send "\r"}
expect "Last" {
    
    send "\r"}
expect "命令" {
    
    send "w\r"}
expect  eof
EOF

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/IHBOS/article/details/114973763