命令 expect 使用
命令 expect 使用
expect 是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式按要求输入指定字符串。
expect 自动交互流程:
-
spawn 启动指定进程
-
expect 获取指定关键字
-
send 向指定程序发送指定字符串
-
执行完成退出
expect 常用命令总结
spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行 expect 后面的程序动作
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的 echo
exit 退出 expect 脚本
eof expect 执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间
示例
ssh 登录远程机器
#!/usr/bin/expect
spawn ssh saneri@192.168.0.1 df -Th
expect "*password"
send "123456\n"
expect eof
expect 执行多条命令
#!/usr/bin/expect -f
set timeout 10
spawn sudo su - root
expect "*password*"
send "123456\r"
expect "#*"
send "ls\r"
expect "#*"
send "df -Th\r"
send "exit\r"
expect eof
参考
Read other posts