1.介绍
expect可以让系统需要人机交互的任务自动化完成,等同于模拟用户输入命令的交互操作,主要用于远程等于服务器并执行命令等人机交互操作
2.安装
- 查看是否安装
rpm -qa expect- 安装
yum install expect
2.工作机制
- 使用spawn开启一个会话,然后使用expect-sen对命令执行人机交互式操作
- spawn 后接命令操作,expect等待输出特定的字符串,然后使用send发送交互字符串
3.基本语法
脚本头部收入引入文件,表名该shell文件用哪种解析器执行
#!/usr/bin/expect
set
- set timeout 超时时间—>设置会话超时时间,若超时时间等于-1,则代表不设置超时时间
set timeout 10s
- set 变量名 变量值—>设置变量
set str “test”
spawn
- spawn 命令 —>开启会话
spawn ssh 192.168.47.41
expect -send
- 接收命名执行后的输出,对输出字符进行匹配,执行响应的操作(输入指定的字符串)
expect {
“yes/no” {send “yes\r”;exp_continue}
“*password” {send “123456\r”}
}
send_user
-后面接输出内容,用于输出信息,等同于echo
send_user “usage: $argv0 <remote_host> <remote_port> <remote_user> <remote_pwd>”
exp_continue
- exp_continue 附加于某个 expect 判断项之后,可以使该项被匹配后,还能继续匹配该 expect 判断语句内的其他项,类似于控制语句中的 continue 语句
“yes/no” {send “yes\r”;exp_continue}
send
- 执行交互动作,等同于手工输入命令
send “su root”
结束符
- expect eof 等待执行结束
- interact 执行完成后保持交互状态
expect eof 与 interact 二选一
接收参数
- 参数存在于argv中
接收第一个输入参数:set param0 [lindex $argv 0]
$argv 表示参数个数,判断语句:
if { $argv < 1} {具体操作逻辑}
4.实例
- 远程登录服务器
#!/usr/bin/expect
if {$argc != 4} {
send_user "usage: $argv0 <remote_host> <remote_port> <remote_user> <remote_pwd>"
exit
}
#设置超时时间20s
set timeout 20
#接收输入参数
set remote_host [lindex $argv 0]
set remote_port [lindex $argv 1]
set remote_user [lindex $argv 2]
set remote_pwd [lindex $argv 3]
# 远程登录
spawn ssh -p${remote_port} ${remote_user}@${remote_host}
expect {
"yes/no" {send "yes\r";exp_continue}
"*password" {send "${remote_pwd}\r"}
}
#结束
expect eof
执行脚本:
expect remote_login.exp 192.168.47.51 22 root 123456