Interaction-free shell

Interaction-free shell

1. Here Document is free of interaction

Use I/O redirection to provide the command list to interactive programs or commands, 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 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

Two, grammatical format

Command << mark

……

Content——————Incoming content between tags

……

mark

Precautions:

  • 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 after the ending tag
  • The spaces before and after the opening tag will be omitted

Three, examples

1. 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
> Line 1
> Line2
> EOF

Insert picture description here

2. Receive input and print it 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

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

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

Insert picture description here

Insert picture description here

5. Assign the whole value 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.
> Today is Monday.
> $var
> EOF
> )
> echo $myvar

Insert picture description here

Insert picture description here

6. 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.
>Today is Monday.
>$var
>EOF
>)
>echo $myvar

Insert picture description here

Insert picture description here

7. Remove the TAB characters or spaces before each line

> #!/bin/bash
> var="Great! I am going to school!"
> myvar=$(cat <<-'EOF'——————在标记前加”-“,即可抑制个行首TAB或空格
> ​							This is Line 1.
> ​					Today is Monday.
> ​			$var
> EOF
> )
> echo -e "$myvar"

Insert picture description here

Insert picture description here

8. 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 empty commands that are not done above, the content of the middle mark area will not be executed twice, 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’——————多行注释,“:”开头的 Here Document 标记内容不会被执行
> ​							This is Line 1.
> ​					Today is Monday.
>$var
> EOF
> echo myvar

Insert picture description here

Insert picture description here

Four, Expect

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 -1 expect
rpm -q tcl
yum -y install expect

1. Basic commands

(1) Script interpreter

The expect script first introduces the file 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

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, and the user simulates the user's input; this command cannot automatically enter and line feed, usually add \r (carriage return) or \n

Example:

method one:

expect "password" {send "abc123\r"}————The send part of the same line must have {}

Way two:

expect "password"
send "$abc123\r"————the send part does not need to have {}

Way three:

expect supports multiple branches

> expect——————只要匹配了其中一个情况,执行相应的send语句后退出该expect语句
> {
    
    
> "密码1" {
    
    send "abc123\r"}
> "密码2" {
    
    send "123456\r"}
> "密码3" {
    
    send "123123\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.

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. Will not log out of the root user, and 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, if you switch to the root user, you will always be in the root user state, such as ssh to another server, and you will always be at 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

例: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, which means that the expectation is allowed to continue to execute the instruction 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 *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 expect{}, because after the spawn process ends, it will send eof to expect by default, which will lead to expect eof later. Execution error

(8)send_user

send_user means echo command, equivalent to echo

(9) Receive parameters

The expect script can receive the parameters passed from the bash command line and use [lindex $argv n] to get them, where n starts from 0 and represents the first, second, third...parameters respectively

set hostname [lindex $argv 0]———— equivalent to hostname=$1

set password [lindex $argv 1]———— equivalent to password=$2

(10) Expect direct execution

Need to use the expect command to execute the script

Five, examples

su switch user

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

Create user and set password

Embedded execution mode, integrate the expect process into the shell, which is convenient for execution and processing

> #! /bin/bash
>  user=$1
>  password=$2 
>  useradd $user ———— 非交互命令放在expect外面 
>  /usr/bin/expect <<-EOF ———————— 开始免交换执行 , expect开始标志 
>  spawn passwd $user —— 开启-一个进程跟踪passwd命令,expect只能捕捉该进程信息 
>  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 {
    
     
> "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后的命令不起作用 

Create disk without interaction

>#!/bin/bash
>/usr/bin/expect <<EOF
>spawn fdisk /dev/$1
>expect "命令(输入 m 获取帮助)" {
    
    send "n\n"}
>expect "Select (default p)" {
    
    send "p\n"}
>expect "分区号" {
    
    send "\n"}
>expect "起始 扇区" {
    
    send "\n"}
>expect "Last 扇区, +扇区" {
    
    send "\n"}
>expect "命令(输入 m 获取帮助)" {
    
    send "w\n"}
>expect eof
>EOF
>fdisk -l
>mkfs.xfs -f /dev/$11 &>/dev/null
>if [ $? -ne 0 ];then
>echo "未格式化成功,请检查脚本"
>else
>echo "格式化成功"
>fi

Guess you like

Origin blog.csdn.net/weixin_51432789/article/details/111825865