expect介绍
expect是由Don Libes基于Tcl(Tool Command Language)语言开发的,主要应用于自动化交互操作的场景,借助于expect处理交互的命令,可以将交互过程如:ssh、scp、ftp登陆等写在一个脚本上,使之自动化完成。尤其适用于需要对堕胎服务器执行相同操作的环境中,可以大大提高维护人员的工作效率。
expect 用法
语法
expect [选项] [-c cmds] [[ -[f|b] ] cmdfile] [args]
选项:
-c :从命令行执行expect脚本,默认expect是交互执行
示例:expect -c ‘expect “\n” { send “pressed enter\n” }’
[root@localhost ~]# expect -c 'expect "\n" { send "pressed enter\n" }'
pressed enter
[root@localhost ~]# *[]
-d:可以输出调试信息
示例:expect -d ssh.exp
expect 中常用命令
spawn 启动新的进程
send 用于向进程发送字符串
expect 从进程接受字符串
interact 允许用户交互
exp_continue 匹配多个字符串在执行动作后加此命令
- expect最常用的语法(tcl语言:模式-动作
单一分支模式语法
expect “hi” { send “You said hi\n” }
匹配到“hi”后,会输出“You said hi”,并换行
多分支模式语法:
expect "hi" { send "You said hi\n" }\
"Hehe" { send "Hehe yourself\n" }\
"bye" { send "Good bye\n" }
匹配hi,Hehe,bye任意字符串时,执行相应输出。等同如下:
expect {
"hi" send "You said hi\n" }
"Hehe" { send "Hehe yourself\n" }
"bye" { send "Good bye\n" }
}
- 变量
set 变量名 值
例:set IP 1.1.1.1 - 位置参数
set ip [index $argv 0]
set user [index $argv 1]
expect 脚本样例
#!/usr/bin/expect
set ip [index $argv 0]
set user [index $argv 1]
set password [index $argv 2]
set timeout 10
spawn ssh $user@$ip
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$password\n" }
}
expect "]#" {send "exit\n"}
expect eof
./ssh.exp 192.168.1.17 root 123456
脚本执行结果如下:
[root@localhost ~]# ./ssh.exp
spawn ssh root@192.168.1.17
root@192.168.1.17's password:
Last login: Wed Sep 1 13:37:55 2021 from 192.168.1.3
[root@client01 ~]# exit
logout
Connection to 192.168.1.17 closed.
[root@localhost ~]#
脚本中注释掉 expect eof的执行结果如下:
[root@localhost ~]# ./ssh.exp
spawn ssh root@192.168.1.17
root@192.168.1.17's password:
Last login: Wed Sep 1 13:38:37 2021 from 192.168.1.3
[root@client01 ~]# [root@localhost ~]#
shell中引用expect
样例一:批量添加秘钥
#!/bin/bash
while read ip ;do
user=root
password="123456"
expect <<EOF
set timeout 10
spawn ssh-copy-id $user@$ip
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$password\n" }
}
expect "]#" { send "exit\n" }
expect eof
EOF
done < IP