介绍:
expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。
expect自动交互流程:
spawn启动指定进程—expect获取指定关键字—send向指定程序发送指定字符—执行完成退出.
安装:
expect常用命令总结:
1 2 3 4 5 6 7 8 9 10
| spawn 交互程序开始后面跟命令或者指定程序 expect 获取匹配信息匹配成功则执行expect后面的程序动作 send exp_send 用于发送指定的字符串信息 exp_continue 在expect中多次匹配就需要用到 send_user 用来打印输出 相当于shell中的echo exit 退出expect脚本 eof expect执行结束 退出 set 定义变量 puts 输出变量 set timeout 设置超时时间
|
例子1
1 2 3 4 5 6 7 8 9
| #! /usr/bin/expect
set timeout 3 spawn ssh root@X.X.X.X -p 12345 expect "*password*" #期待匹配到 'user_name@ip_string's password:'
send "passwd\r" interact
|
在脚本中使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| /usr/bin/expect << EOF spawn /usr/bin/ssh -t -p 22022 admin@$i "sudo su -"
expect { "yes/no" { send "yes\r" } }
expect { "password:" { send "xxo1#qaz\r" } }
expect { "*password*:" { send "xx1#qaz\r" } } expect eof
EOF
|
参考:https://www.cnblogs.com/saneri/p/10819348.html