shell脚本系列:expect脚本

参数说明:

  • set:可以设置超时,也可以设置变量
  • timeout:expect超时等待时间,默认10S
  • spawn:执行一个命令
  • expect "":匹配输出的内容
  • exp_continue:继续执行下面匹配
  • :可以理解为回车
  • $argc:统计位置参数数量
  • [lindex $argv 0]:脚本后第一个参数,类似于shell中$1,以此类推
  • puts:打印字符串,类似于echo
  • awk -v I="$ip":赋值变量
  • expect{...}:输入多行记录

其他参数说明:

  • timeout -1:永不超时退出
  • log_file /var/log/expect.log:记录交互信息,一般crontab时使用
  • interact:交互后不退出远程终端,如果加要把expect "root@*" {send "exit "}注释掉,如果不加,就直接退出
  • 将spawn ssh root@$ip换成spawn ssh -o StrictHostKeyChecking=no root@ip既不会再提示是否将服务器计算机密钥加入本地known_hosts

示例:

shell内嵌类型:

#!/bin/bash
/usr/bin/expect << EOF
spawn /bin/su -
expect "Password: "
send "123
"
expect "*#"
interact
expect eof
EOF

分离型:

vi login.exp
#!/usr/bin/expect 
set ipaddress [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]

if { $argc != 3 } {
puts "Usage: expect login.exp ipaddress username password"
exit 1
}

set timeout 30
spawn ssh $username@$ipaddress
expect {
        "(yes/no)" {send "yes
"; exp_continue}
        "password:" {send "$password
"}
}

expect "$username@*"  {send "df -h
"}
expect "$username@*"  {send "exit
"}
expect eof
vi user_info
192.168.1.156   user    user
192.168.1.154   root    123.com
vi expect.sh
#!/bin/bash
for ip in `awk '{print $1}' user_info`
do
    user=`awk -v I="$ip" '{if(I==$1)print $2}' user_info`
    pass=`awk -v I="$ip" '{if(I==$1)print $3}' user_info`
    expect login.exp $ip $user $pass
done
原文地址:https://www.cnblogs.com/iuskye/p/shell-expect.html