利用Expect来实现自动交互
注意:需提前安装 expect
- CentOS
# 安装 expect
[root@ansible ~]# yum -y install expect
# 查看安装包
[root@ansible ~]# rpm -qa expect
expect-5.45-14.el7_1.x86_64
- Ubuntu
# apt-get install expect -y
run_cmd.exp 脚本解决ssh交互问题
#!/usr/bin/expect
if { $argc !=2 } {
puts "Usages: expect $argv0 ip command"
exit
}
# 接收脚本参数
set ip [lindex $argv 0]
set cmd [lindex $argv 1]
# 配置 SSH 密码,每台服务器的SSH密码必须一致
set password "test"
spawn ssh root@$ip $cmd
# 匹配交互内容
expect {
"yes/no" {send "yes\r";exp_continue}
"*password" {send "$password\r"}
}
expect eof
run_cmd.sh 利用 shell 循环执行 Expect 脚本命令
#!/bin/bash
#Author:mcsiberiawolf
#Time:2019-02-13 09:42:25
#Name:run_cmd.sh
#Version:V1.0
#Description: This is a test script.
if [ $# -ne 1 ]; then
echo $"Usage: $0 cmd"
exit 1
fi
cmd=$1
# 192.168.7.2和192.168.7.3 批量执行命令
for n in 2 3
do
/usr/bin/expect /server/scripts/expect/run_cmd.exp 192.168.7.$n "$cmd"
done
批量查看及其负载
[root@ansible expect]# sh run_cmd.sh uptime
spawn ssh root@192.168.7.2 uptime
root@192.168.7.2's password:
10:01:31 up 13 days, 16:15, 1 user, load average: 0.04, 0.17, 0.21
spawn ssh root@192.168.7.3 uptime
root@192.168.7.3's password:
10:01:49 up 13 days, 16:14, 0 users, load average: 0.22, 0.28, 0.23
批量查看内存
[root@ansible expect]# sh run_cmd.sh "free -m"
spawn ssh root@192.168.7.2 free -m
root@192.168.7.2's password:
total used free shared buff/cache available
Mem: 112517 992 111031 17 493 110893
Swap: 15259 0 15259
spawn ssh root@192.168.7.3 free -m
root@192.168.7.3's password:
total used free shared buff/cache available
Mem: 128644 1057 127094 17 493 126954
Swap: 15259 0 15259
批量查看 /etc/passwd 文件
[root@ansible expect]# sh run_cmd.sh "ls -al /etc/passwd"
spawn ssh root@192.168.7.2 ls -al /etc/passwd
root@192.168.7.2's password:
-rw-r--r--. 1 root root 874 Jan 30 17:12 /etc/passwd
spawn ssh root@192.168.7.3 ls -al /etc/passwd
root@192.168.7.3's password:
-rw-r--r--. 1 root root 874 Jan 30 17:12 /etc/passwd