expect

expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。

expect自动交互流程:

spawn启动指定进程---expect获取指定关键字---send向指定程序发送指定字符---执行完成退出.

注意该脚本能够执行的前提是安装了expect
expect用法
-c 从命令行执行expect脚本,默认expect是交互地执行的

expect常用命令
spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行expect后面的程序动作
send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect 执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间

变量设置
set 变量名 变量值
例如:
set user root
打印变量
put $user

特殊变量
expect也有同shell脚本里$0 $1 $2类似的特殊变量,用于接收及控制Expect脚本传参
可以使用[lindex $argv n]接收脚本传参,n从0开始,分别表示第一个[lindex $argv 0]参数,第二个参数[lindex $argv2]... 依次类推
$argc表示参数的个数
$argv0表示脚本名称

[root@kafka-server01 scripts]# cat 1.exp                        
#!/usr/bin/expect


set ip [lindex $argv 0]
set cmd [lindex $argv 1]
set password "123456"
set timeout -1

send_user "第一个参数:$ip
"
send_user "第二个参数:$cmd
"
puts "$password
"
send_user "参数个数: $argc
"
send_user "脚本名称: $argv0
"

[root@kafka-server01 scripts]# expect 1.exp 127.0.0.1 'nihao'
第一个参数:127.0.0.1
第二个参数:nihao
123456

参数个数: 2
脚本名称: 1.exp

shell脚本

[root@kafka-server01 scripts]# cat /root/scripts/info 
192.168.37.131 root 123456
192.168.37.132 root 123456

[root@kafka-server01 scripts]# cat 4.sh
#!/bin/bash
file=/root/scripts/info
while read line;do
    user=$(echo $line | cut -d " " -f 2)
    ip=$(echo $line |cut -d " " -f 1)
    passwd=$(echo $line|cut -d " " -f 3)
    cmd=$*
    # echo "-------$user -- $ip -- $passwd"
    expect <<EOF
          set timeout -1
          spawn ssh $user@$ip
          expect {
                "yes/no" { send "yes
";exp_continue }
                "password" { send "$passwd
";exp_continue }
                "root" {send "$cmd
 exit
"}
          }
      expect eof
EOF
done <$file

[root@kafka-server01 scripts]# sh 4.sh 'free -h'
spawn ssh root@192.168.37.131
Last login: Thu Sep 30 11:36:58 2021 from 192.168.37.130
[root@kafka-server02 ~]# free -h
              total        used        free      shared  buff/cache   available
Mem:           1.8G        564M        668M         33M        597M        1.0G
Swap:          1.5G          0B        1.5G
[root@kafka-server02 ~]#  exit
登出
Connection to 192.168.37.131 closed.
spawn ssh root@192.168.37.132
Last login: Thu Sep 30 11:36:58 2021 from 192.168.37.130
[root@kafka-server03 ~]# free -h
              total        used        free      shared  buff/cache   available
Mem:           1.8G        557M        1.0G         41M        244M        1.0G
Swap:          1.5G          0B        1.5G
[root@kafka-server03 ~]#  exit
登出
Connection to 192.168.37.132 closed.
[root@kafka-server01 scripts]# 

  

原文地址:https://www.cnblogs.com/zhouzhiguo/p/15356693.html