expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。
sudo apt-get update
sudo apt-get install expect
Expect中最关键的四个命令是send,expect,spawn,interact。
一般流程:spawn 启动追踪 —> expect 匹配捕捉关键字 ——> 捕捉到将触发send 代替人为输入指令—> interact /expect eof
Expect脚本必须以interact或expect eof 结束,执行自动化任务通常expect eof就够了
expect eof 是在等待结束标志。由spawn启动的命令在结束时会产生一个eof标记,expect eof 即在等待这个标记
使用<<-EOF
,引入expect脚本。
#!/bin/base
/usr/bin/expect <<-EOF
EOF
1). 开始构建文件
vi test_expect.exp
2). 构建文件内容
#!/usr/bin/expect
# 传入参数数量验证
if {$argc < 3} {
#do something
send_user "usage: $argv0 <remote_user> <remote_host> <remote_pwd>"
exit
}
// 将超时设置为-1以禁用超时功能。
set timeout -1
# 远程服务器用户名
set remote_user [lindex $argv 0]
# 远程服务器域名
set remote_host [lindex $argv 1]
# 远程服务器密码
set remote_pwd [lindex $argv 2]
# 远程登录
spawn ssh ${remote_user}@${remote_host}
expect {
"*password" {send "${remote_pwd}\r";}
"*yes/no" {send "yes\r";exp_continue}
}
# ssh登陆成功后,继续进行操作。
expect "]#" { send "cd /\r" }
# 结束
expect eof
3). 使用脚本
./test_expect.exp username ip password
#!/usr/bin/expect
。