标签:expect
expect介绍
expect命令是一个实现交互功能的软件套件,是基于TCL的脚本编程语言,在企业运维中,系统会以交互的形式要求运维人员输入指定的字符串,之后才能继续执行命令。例如:为用户设置密码时,一般情况下需要手工输入两次密码,比如使用ssh连接远程服务器时,第一次连和系统实现两次交互。
简单的说,expect用来自动实现与交互程序通信的,无需管理员手工干预
spawn启动指定进程>expect获取期待的关键字>send向指定进程发送字符>进程执行完毕,退出
expect 表达式 [动作]
在expect自动交互的执行过程中,当使用spawn命令执行一个命令或程序之后,会提示某些交互信息,expect命令的作用就是获取spawn命令执行的信息,看看是否有事先指定的相匹配,一旦匹配上指定的内容就执行expect后面的动作。
#安装expect
[root@server1 ~]# yum install -y expect
#样例
#当需要ssh到一台主机时,会出现如下信息,显然这个是要人工输入,这里就可以用expect实现交互
[root@server1 ~]# ssh 192.168.174.134 The authenticity of host ‘192.168.174.134 (192.168.174.134)‘ can‘t be established. ECDSA key fingerprint is f1:bb:26:4a:70:d0:66:7c:96:07:54:eb:ea:fc:06:1b. Are you sure you want to continue connecting (yes/no)?
#expect 脚本
[root@server1 ~]# cat ssh.sh #!/usr/bin/expect spawn ssh root@192.168.174.135 expect "yes/no" send "yes\r" expect "password:" send "redhat\r" expect "]#" interact [root@server1 ~]#
#运行脚本
[root@server1 ~]# expect ssh.sh spawn ssh root@192.168.174.135 The authenticity of host ‘192.168.174.135 (192.168.174.135)‘ can‘t be established. ECDSA key fingerprint is 89:17:ab:61:5e:1b:30:29:3e:42:c8:0e:8d:ce:01:df. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added ‘192.168.174.135‘ (ECDSA) to the list of known hosts. root@192.168.174.135‘s password: Last failed login: Fri Jun 30 23:53:01 CST 2017 from 192.168.174.134 on ssh:notty There was 1 failed login attempt since the last successful login. Last login: Fri Jun 30 23:52:37 2017 from 192.168.174.1 [root@KVM_2 ~]#
#可以看到当运行expect脚本时,遇到交互界面时,系统没有停留等待用户交互,而是自动完成交互
spawn 启动新的进程
expect 接受字符串
send 发送字符串(\r 回车)
interact 允许用户交互
(未完成,有空更)
本文出自 “Chauncey” 博客,请务必保留此出处http://cqwujiang.blog.51cto.com/10808946/1943526
标签:expect
原文地址:http://cqwujiang.blog.51cto.com/10808946/1943526