expect

来源:互联网 发布:蜗牛游戏 知乎 编辑:程序博客网 时间:2024/05/08 17:34

一.概述

expect可以实现自动和交互式任务进行通信。


二.常用使用方法

1.#!/usr/bin/expect                           

指定使用的shell;


2.set timeout 10                             

设置超时时间为10s,如果设置为-1,则表示永不超时


3.spawn command                        

spawn是expect的内部命令,可以理解为expect的入口;


4.log_file log_name                      

指定日志文件为log_name,记录输出信息;


5.log_user 1

设置是否显示输出信息,设置为1时是缺省值,特别注意:为0时,expect不产生任何输出信息,同时关闭了对记录文件的输出;


6.expect "passwd:"

判断上次输出结果里是否有字符串passwd,有的话立即返回,常和send一起使用,否则就等待一段时间后返回,等待时间为设置的超时时间;


7.send "passwd\r"

执行交互动作,向终端发送passwd,相当于手工输入,其中\r模拟回车;


8.exp_continue

可以继续执行下面的匹配;


9.set user [lindex $argv 0]

向expect传递第一个参数user,执行:./test.exp $user;


10.expect eof

spawn 命令出现交互式提问的但是expect 匹配不上的话,那么程序会按照timeout的设置进行等待;可是如果spawn 直接发出了eof 也就是本例的情况,那么expect"assword"将不会等待,而直接去执行expect eof;


11.可以在shell脚本中调用expect脚本

#!/bin/bash

...

expect test.exp $1 $2...> log_file


12.也可以在shell脚本中直接写入

#!/bin/bash

...

/usr/bin/expect << EOD

log_file ...

log_user ...

spawn ...

...

expect eof

EOD


13.个人常用于需要通过linux服务器取网络设备数据的时候。


三.安装

1.Tcl 安装

下载地址: http://www.tcl.tk/software/tcltk/downloadnow84.tml


1)下载源码包:wget http://nchc.dl.sourceforge.net/sourceforge/tcl/tcl8.4.11-src.tar.gz


2)解压:tar -zxvf tcl8.4.11-src.tar.gz


3)安装配置
cd tcl8.4.11/unix
./configure --prefix=/usr/tcl --enable-shared
make
make install

cp tcl8.4.11/unix/tclUnixPort.h tcl8.4.11/generic


2.expect 安装


1)下载源码包:wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz/download


2)解压:tar -zxvf expect5.45.tar.gz


3)安装

cd expect5.45
./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.4.11/generic

make
make install
ln -s /usr/tcl/bin/expect /usr/bin/expect


3.测试

输入expect出现命令行,表示安装成功。


安装部分参考:http://blog.chinaunix.net/uid-20639775-id-2453085.html


1 0
原创粉丝点击