一、介绍
expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。
expect自动交互流程:
- spawn启动指定进程
- expect获取指定关键字
- send向指定程序发送指定字符
- 执行完成退出 eof
二、安装和命令
安装
yum install -y expect
常用命令
spawn 交互程序开始后面跟命令或者指定程序
expect 关键字匹配
send exp_send 发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间
脚本执行
1)声明 expect
脚本开头需声明
#!/usr/bin/expect
使用 expect xxx.sh 或者 ./xxx.sh 执行脚本
2)声明 bash
仍使用 bash 声明
#!/bin/bash
将 expect 命令部分包起来
/usr/bin/expect <<-EOF
xxxxx....
EOF
使用 sh xxx.sh 或者 ./xxx.sh 执行脚本
三、示例
远程登录主机
简单版本
#!/usr/bin/expect
spawn ssh xxx@192.168.xx.xx # spawn 后面跟要执行的命令
expect "password" # expect 后跟关键字,匹配上面命令执行后出现的提示字符串
send "123456\n" # 最后需要一个换行符 \r 或者 \n
expect eof # 表明结束(必要)
多命令匹配
#!/usr/bin/expect
spawn ssh xxx@192.168.xx.xx
expect {
"yes/no" { send "yes\r"; exp_continue }
"password:" { send "$passwd\r" }
}
expect eof
参考文章:
Linux expect 介绍和用法一
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。