- 工信部备案号 滇ICP备05000110号-1
- 滇公网安备53011102001527号
- 增值电信业务经营许可证 B1.B2-20181647、滇B1.B2-20190004
- 云南互联网协会理事单位
- 安全联盟认证网站身份V标记
- 域名注册服务机构许可:滇D3-20230001
- 代理域名注册服务机构:新网数码
- CN域名投诉举报处理平台:电话:010-58813000、邮箱:service@cnnic.cn
如果想写一个能够自动处理输入输出的脚本又不想面对C或Perl,那么expect是最好的选择。它可以用来做一些Linux下无法做到交互的一些命令操作。
(1).安装和使用expect
expect是不会自动安装的所以需要使用命令进行安装,这里使用yum即可:
1 | [root@xuexi ~]# yum -y install expect |
在脚本中使用expect的方法一般有两种:
第一种、定义脚本执行的shell时,定义为expect。即脚本第一行为#!/bin/expect或#!/usr/bin/expect;
第二种、在shell脚本中使用时,可以使用一组/usr/bin/expect< (2).expect中参数和语法说明 set [变量名] "[String]" 在expect脚本中设置变量需要在前面使用set,否则无法使用。 set timeout 30 设置超时时间,单位为秒,如果设为timeout -1则永不超时。 spawn spawn是进入expect环境后才能执行的内部命令,如果没有安装expect或直接在默认shell下执行是找不到spawn命令的。它主要的功能是开启脚本和命令之间的会话。(后面跟随的命令必须是需要交互的,因为expect脚本是用来做交互应用的) expect 这里的expect同样是expect的内部命令。主要功能是判断输出结果是否包含某项关键字,没有则立即返回,否则等待一段时间后返回,等待时间通过set timeout进行设置。有两种写法: send 执行交互动作,将交互要执行的动作输入。命令字符串结尾要加上"\r",如果出现异常等待状态可以进行核查 exp_continue 继续执行接下来的交互操作 interact 执行完后保持交互状态,把控制权交给控制台;如果没有这一项,交互完成后会自动退出 $argv expect脚本可以接受从bash传递过来的参数,可以使用[Iindex $argv n]获得,n从0开始表示第一个参数。 注意:spawn开启会话,expect和send进行交互。 (3).脚本实例 1)expect脚本实现ssh免交互 在192.168.1.6上可以看到生成了/root/1.txt 2)shell脚本实现免交互 售前咨询 售后咨询 备案咨询 二维码 TOPexpect{ "[String1]" {send "[sendString1]\r";exp_continue} "[String2]" {send "[sendString2]\r";exp_continue} ... "[StringN]" {send "[sendStringN]\r"}}或expect "String"send "sendString1\r"sned "sendString2\r"...expect eof[root@xuexi ~]# cat ssh-6.exp#!/bin/expectset ipaddr "192.168.1.6"set name "root"set passwd "123456"set timeout 30spawn ssh $name@$ipaddrexpect "password"send "$passwd\r"expect eofexpect "#"send "ls /etc/ >> /root/1.txt\r"send "exit\r"expect eof[root@xuexi ~]# expect ssh-6.expspawn ssh root@192.168.1.6root@192.168.1.6's password:Last login: Sat May 11 18:24:27 2019 from xuexi[root@youxi1 ~]# ls /etc/ >> /root/1.txt[root@youxi1 ~]# exit登出Connection to 192.168.1.6 closed.[root@xuexi ~]# cat ssh-6.sh#!/bin/bashname="root"passwd="123456"ipaddr="192.168.1.6"/bin/expect << EOFset timeout 30spawn ssh $name@$ipaddrexpect "password"send "$passwd\r"expect eofexpect "#"send "ls /etc/ >> /root/2.txt\r"send "exit\r"expect eofEOF[root@xuexi ~]# sh ssh-6.shspawn ssh root@192.168.1.6root@192.168.1.6's password:Last login: Sat May 11 19:21:18 2019 from xuexi[root@youxi1 ~]# ls /etc/ >> /root/2.txt[root@youxi1 ~]# exit
