expect实现免交互

  如果想写一个能够自动处理输入输出的脚本又不想面对C或Perl,那么expect是最好的选择。它可以用来做一些Linux下无法做到交互的一些命令操作。

(1).安装和使用expect

  expect是不会自动安装的所以需要使用命令进行安装,这里使用yum即可:

[root@xuexi ~]# yum -y install expect

  在脚本中使用expect的方法一般有两种:

    第一种、定义脚本执行的shell时,定义为expect。即脚本第一行为#!/bin/expect或#!/usr/bin/expect;

    第二种、在shell脚本中使用时,可以使用一组/usr/bin/expect<<EOF和EOF来对expect调用。

(2).expect中参数和语法说明

  set [变量名] "[String]"

  在expect脚本中设置变量需要在前面使用set,否则无法使用。

  set timeout 30

  设置超时时间,单位为秒,如果设为timeout -1则永不超时。

  spawn

  spawn是进入expect环境后才能执行的内部命令,如果没有安装expect或直接在默认shell下执行是找不到spawn命令的。它主要的功能是开启脚本和命令之间的会话。(后面跟随的命令必须是需要交互的,因为expect脚本是用来做交互应用的

  expect

  这里的expect同样是expect的内部命令。主要功能是判断输出结果是否包含某项关键字,没有则立即返回,否则等待一段时间后返回,等待时间通过set timeout进行设置。有两种写法:

expect{
    "[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

  send

  执行交互动作,将交互要执行的动作输入。命令字符串结尾要加上"\r",如果出现异常等待状态可以进行核查

  exp_continue

  继续执行接下来的交互操作

  interact

  执行完后保持交互状态,把控制权交给控制台;如果没有这一项,交互完成后会自动退出

  $argv

  expect脚本可以接受从bash传递过来的参数,可以使用[Iindex $argv n]获得,n从0开始表示第一个参数。

  注意:spawn开启会话,expect和send进行交互。

(3).脚本实例

 1)expect脚本实现ssh免交互

[root@xuexi ~]# cat ssh-6.exp
#!/bin/expect
set ipaddr "192.168.1.6"
set name "root"
set passwd "123456"
set timeout 30
spawn ssh $name@$ipaddr
expect "password"
send "$passwd\r"
expect eof
expect "#"
send "ls /etc/ >> /root/1.txt\r"
send "exit\r"
expect eof
[root@xuexi ~]# expect ssh-6.exp 
spawn ssh root@192.168.1.6
root@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.

  在192.168.1.6上可以看到生成了/root/1.txt

2)shell脚本实现免交互

[root@xuexi ~]# cat ssh-6.sh 
#!/bin/bash

name="root"
passwd="123456"
ipaddr="192.168.1.6"

/bin/expect << EOF
set timeout 30
spawn ssh $name@$ipaddr
expect "password"
send "$passwd\r"
expect eof
expect "#"
send "ls /etc/ >> /root/2.txt\r"
send "exit\r"
expect eof
EOF
[root@xuexi ~]# sh ssh-6.sh 
spawn ssh root@192.168.1.6
root@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
登出
Connection to 192.168.1.6 closed.

  在192.168.1.6上可以看到生成了/root/2.txt

 

posted @ 2019-05-12 13:33  苦逼运维  阅读(942)  评论(0编辑  收藏  举报