Home  >  Article  >  Operation and Maintenance  >  How to implement Linux Shell automatic interaction function

How to implement Linux Shell automatic interaction function

PHPz
PHPzforward
2023-05-29 12:43:182418browse

Demand background:

Recently, during the installation process of a certain software, I found that some information needs to be entered during the installation process to continue the next step. When the number of machines is small, we can log in to complete the installation on a single machine. However, when the number of machines exceeds a certain level, manual login operations will produce a large number of repetitive operations, which will not improve effective learning capabilities, but will also greatly generate uncertainty and cause a decrease in work efficiency. So how? What about automating certain operations, especially steps with interactive functions, such as the need to enter an account and password?

1. EOF multi-text input

Requirement case 1

A new batch of machines have been delivered. Each machine is only allocated one disk. Now the disk is allocated according to the demand. How to partition and mount?

Requirement analysis:

For a disk, to mount partitions to different directories, there are usually two ideas:

Method 1: Use the entire disk as a PV, Integrate it into a VG volume, and then divide it into different directories according to the size of different LV volumes. Method 2: Use fdisk to directly divide the disk into the corresponding size, then initialize the disk and complete the mounting.

Solution

Here we choose method two to demonstrate the interactive function. The implementation script is as follows:

#!/bin/bash
fdisk /dev/sdb <<EOF
n
p
1
wq
EOF
 
 mkfs.xfs /dev/sdb1 &&  mkdir -p /data && mount /dev/sdb1 /data
echo &#39;/dev/sdb1 /data xfs defaults 0 2&#39; >> /etc/fstab

Analyzing the above script, we found that a keyword EOF

    # is used
  • ##EOF is the abbreviation of END Of File, which means a custom terminator. Since it is customized, EOF is not fixed. You can set an alias at will. In Linux, press ctrl-d to represent EOF. .

  • EOF usually works with cat to output multi-line text.

Its usage As follows:

.... //What needs to be entered

EOF //End

For example, use

cat, , and > to write bash scripts interactively, as shown below.

cat << EOF > script.sh
#!/bin/bash
 
printf "Hello\n"
printf "Wordl!\n"
EOF

How to implement Linux Shell automatic interaction function

How to implement Linux Shell automatic interaction function

Reasonable use of these three can complete the corresponding multi-text interactive input, such as changing user passwords. Under normal circumstances, it is necessary Enter the password twice in a row. Only if the two passwords are consistent can the change be successful, as follows:

How to implement Linux Shell automatic interaction function

We learned the keyword EOF above, so let’s try to use it to change the password. The script is as follows:

#!/bin/bash
 
cat << EOF| passwd 
新密码
新密码,与上述需一致
EOF
 
# or 不使用管道符
 
passwd << EOF
新密码
新密码,与上述需一致
EOF

Actual results, successfully changed the password:

How to implement Linux Shell automatic interaction function

2. Expect automatic interaction

Requirement case 2

  A batch of newly delivered machines needs to be distributed to each machine. How to achieve this?

Requirement analysis:

The commonly used password for remote copying files is scp or rsync, but when transferring to each machine, you need to enter a password. Some machines may also need to enter YES and enter the machine fingerprint. The information is as follows:

How to implement Linux Shell automatic interaction function

Expect is an automated interactive suite based on tcl. In some scenarios that require interactive input of instructions, interactive communication can be automatically performed through script settings. The interaction process mainly has the following five steps:

0 Define variables

1 spawn to start the specified script or command

2 expect to match the result keyword

3 sendSends the specified command for the specified keyword

4 Execution completed, exit

But unfortunately, os is not installed by default, so it needs to be installed before using

Expect is a tcl application for automating and testing interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, etc. Expect makes it easy for a script to control another program and interact with it.

Solution:

1. First check whether expect is installed on this machine. If it is not installed, you need to install it manually

# 检查是否安装了expect:
[root@localhost ~]# rpm -qi expect
Name        : expect
Version     : 5.45
Release     : 14.el7_1
Architecture: x86_64
Install Date: Fri 05 Aug 2022 07:26:04 AM CST
Group       : Development/Languages
....
 
# 如果没有安装, 使用yum安装expect ,通常会顺带把依赖包tcl 也安装了:
[root@localhost ~]# yum install -y expect  # -y  其实也是安装过程中一个交互,发现没,只是作为参数传入了
[root@localhost ~]# yum install -y tcl  # 如果上述命令提示已安装tcl了,此步可以忽略
 
# 查看expect的安装路径:
[root@localhost ~]#  which expect
/usr/bin/expect

2. Corresponding function script development, the reference for this case script is as follows:

[root@test01 ~]# cat scp.exp
#! /usr/bin/expect
set file [lindex $argv 0]
set file2 [lindex $argv 1]
spawn scp -rp $file $file2 root@192.168.31.89:/tmp
expect {
 "(yes/no)" {send "yes\r";exp_continue}
 "*password:*" {send "Password\r"}
 
}
expect eof
exit -onexit {
 send_user "bye \n"
}

3. Analyzing the above script, there are several points that need to be explained.

#!/usr/bin/expect

The first line of the script file indicates the expect installation location. For details, please refer to the command in 2 to specify the script parser and Shell. Similar, it means that the program uses Expect parsing, which is different from the general bash script, so it needs to be noted that usually we will change the expect script suffix to exp to distinguish it from the bash script sh

set Set variable value

set file [lindex $argv 0] Assign the first parameter passed in to file, similar to the second and third parameters [lindex $argv 1] [lindex $argv 2] etc. Use $file for subsequent calls, the same as shell. Special parameters:

$argc represents the number of passed parameters, $argv0 represents the name of the script

spawn table name is the script to be executed or Program commands, such as ssh, scp, etc.

格式: spawn [选项] [需要自动交互的命令或程序]

例如:spawn scp -rp $file $file2 root@192.168.31.89:/tmp #<==执行scp命令(注意开头必须要有spawn, 否则无法实现交互)

expect

需和spawn 配合使用 ,表示匹配spawn指定的脚本或命令的输出结果,如果与expect后面的字符串匹配,就执行下面的send命令,表示对结果响应反馈

有时命令的输出提示信息有可能会变化,所以可以在expect中使用模糊匹配,比如*

注意:匹配的动作也可以放在下一行,这样就不需要使用{}(大括号)了

send

在expect命令匹配指定的字符串后,发送指定的字符串给系统,这些命令可以支持一些特殊转义符号,例如:\r表示回车、\n表示换行、\t表示制表符等

exp_continue

从命令的拼写就可以看出命令的作用,即让Expect程序继续匹配的意思,如果需要一次匹配多个字符串,那么不同的匹配之间就要加上exp_continue,否则expect将不会自动输入指定的字符串。由于前面的都已经完成,最后一个不必加上exp_continue,它已经是最后一个了

exit

功能类似于Shell中的exit,即直接退出脚本,还可以利用这个命令对脚本做一些关闭前提示等工作

send_user

打印Expect脚本信息,类似Shell里的echo. 例如打印变量信息,验证数据传入是否正常

在掌握expect 基本使用方式后,我们写一个批量查看机器负载信息的小脚本,加强记忆

#! /usr/bin/expect
    set time 30
    set ip [lindex $argv 0]
 
    spawn ssh root@$ip uptime
    expect {
        "*yes/no" { send "yes\r"; exp_continue }
        "*password:" { send "$password\r" }
    }
    expect eof

实战结果:

How to implement Linux Shell automatic interaction function

小试牛刀

在学习完以上两个方法,我们试着写一个脚本,结合上述两种方式,批量查看各机器目录挂载情况,并列举出来,参考脚本如下:

#!/bin/bash
 
ip="192.168.31.89"
username="root"
password="123456"
cmd=" df -PTh|grep ^/dev"
# 指定执行引擎
expect <<EOF
    set time 30
    spawn ssh $username@$ip  $cmd
    expect {
        "*yes/no" { send "yes\r"; exp_continue }
        "*password:" { send "$password\r" }
    }
    expect eof
EOF

The above is the detailed content of How to implement Linux Shell automatic interaction function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete