expect是建立在tcl基础上的一个工具,它可以让一些需要交互的任务自动化完成。
安装 yum –y install expect
工作原理:
首先用spawn开启一个会话,然后用expect-send执行交互操作
spawn后面跟上一个命令操作,表示开启一个会话。expect等待输出特定的字符串,然后用send发送交互字符串。
例:
expect “*assword”提示为”username@host’s password:”等待用户输入密码
send “${password}\r”使用send模拟用户输入密码的字符串
开头必须写#!/usr/bin/expect
set
1>set timeout 30 设置会话时间30,若不限时间设为-1
2>set设置参数 set param “param1” 获取参数${param}
expect
接受命令执行后的输出,然后和期望的字符串匹配
例:expect “$case1”{send “$respond\r”}
结束符
expectof 等待命令执行结束,若没有,可能导致命令还没执行,脚本就结束le
interact 执行完成后保持交互状态,可以手动输入信息
两者二选一即可
expect_continue跳出本次循环
参数
$argc 表示参数个数,可进行判断
if {$argc < 1} { #do something send_user "usage: $argv0 <param1> <param2> ... " exit }
$argv0表示脚本名
[lindex $argv0]表示第一个参数
[lindex $argv1]表示第二个参数
send_user 标准输出
#!/usr/bin/expect set ip [lindex $argv 0] set password [lindex $argv 1] set timeout -1 spawn ssh root@$ip expect { "password" {send "$password\r";} "yes/no" {send "yes\r";exp_continue} } expect "root" {send "mkdir test1\r"} expect "root" {send "mkdir test2\r"} send "exit\r" //退出远程登录 expect eof