expect介绍
expect 是一个免费的编程工具,用来实现自动的交互式任务,而无需人为干预。说白了, expect
就是一套用来实现自动交互功能的软件。需要安装
1 |
yum install -y expect |
命令 | 作用 |
---|---|
spawn | 启动新的进程 |
expect | 从进程接收字符串 |
send | 用于向进程发送字符串 |
interact | 允许用户交互 |
1 2 3 4 5 6 |
● spawn 命令用来启动新的进程, spawn 后的 expect 和 send 命令都是和使用 spawn 启动的新进程进行交互。 ● expect 通常用来等待一个进程的反馈,我们根据进程的反馈,再使用 send 命令发送对应的交互命令。 ● send 命令接收一个字符串参数,并将该参数发送到进程。 ● interact 命令用的其实不是很多,一般情况下使用 spawn 、 expect 和 send 和命令就可以很好的完成我们的任务;但在一些特殊场合下还是需要使用 interact 命令的, interact 命令主要用于退出自动化,进入人工交互。比如我们使用 spawn 、 send 和 expect 命令完成了ftp登陆主机,执行下载文件任务,但是我们希望在文件下载结束以后,仍然可以停留在ftp命令行状态,以便手动的执行后续命令,此时使用 interact 命令就可以很好的完成这个任务。 |
expect实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/usr/bin/bash user="root" ip="127.0.0.1" cmd="uptime" pass="1" expect << EOF spawn ssh $user@$ip $cmd set timeout 3 # 超过了3秒,无论是否匹配成功都会继续执行下一条指令 # 设置为-1代表永不超时,如果expect没有捕捉到就一直停在原地 expect { "yes/no" {send "yes\n";exp_continue} # 继续下一个操作 "password" {send "$pass\n"} } expect eof EOF |
interact交互
执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。如果没有这一句登录完成后会退出,而不是留在远程终端上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# 使用interact交互必须是expect解释器 # 执行完命令不会返回 [root@clf ~]# cat test.sh #!/usr/bin/expect -f spawn ssh root@10.0.0.5 expect { "yes/no" {send "yes\r";exp_continue} "password" {send "1\n"} } expect { "lb02" {send "ls\n"} } expect { "lb02" {send "pwd\n"} } interact |