一、概述
expect是Unix系统中用来进行自动化控制和测试的软件工具,由Don Libes制作,作为Tcl脚本语言的一个扩展,应用在交互式软件中如telnet,ftp,Passwd,fsck,rlogin,tip,ssh等等。该工具利用Unix伪终端包装其子进程,允许任意程序通过终端接入进行自动化控制;也可利用Tk工具,将交互程序包装在X11的图形用户界面中。
我们通过Shell可以实现简单的控制流功能,如:循环、判断等。但是对于需要交互的场合则必须通过人工来干预,比如普通用户使用sudo命令时就需要我们手动输入密码;expect就是能够完成这种自动交互任务,而无需人的干预。Expect的作者Don Libes在1990年开始编写Expect时对Expect做有如下定义:Expect是一个用来实现自动交互功能的软件套件(Expect [is a] software suite for automating interactive tools)。系统管理员可以使用它创建用来实现对命令或程序提供输入的脚本:一般来说这些输入都需要手工输入(比如之前提到的执行sudo程序期望用户从终端输入用户密码)进行的,Expect则可以根据程序的提示 模拟标准输入给程序提供信息来实现交互程序执行。甚至可以实现简单的BBS聊天机器人。
Expect是不断发展的,随着时间的流逝,其功能越来越强大,已经成为系统管理员的的一个强大助手。Expect需要Tcl编程语言的支持,要在系统上运行Expect必须首先安装Tcl。
二、工作原理
Chat脚本由一系列 expect-send对组成:
expect "Login:"
send "somebody\n"
# expect等待"Password:",使用send回应111111
expect "Password:"
send "111111\n"
三、应用
3.1自动登陆ssh服务器
使用expect实现自动登录的脚本,网上有很多,可是都没有一个明白的说明,初学者一般都是照抄、收藏。可是为什么要这么写却不知其然。本文用一个最短的例子说明脚本的原理。
set timeout 30
spawn ssh test@127.0.0.1
expect "password:"
send "123456\n"
interact
spawn ssh test@127.0.0.1
test@127.0.0.1 's password:
Linux gyl 2.6.32-46-generic #108-Ubuntu SMP Thu Apr 11 15:55:01 UTC 2013 i686 GNU/Linux
Ubuntu 10.04.4 LTS
Welcome to Ubuntu!
* Documentation: https://help.ubuntu.com/
New release 'precise ' available.
Run 'do-release-upgrade ' to upgrade to it.
Last login: Sat May 11 01:08:19 2013 from localhost
$
3.2封装scp语句实现上传下载的自动交互
#
#auto down/up files from/to server over scp.protocol
#Usage:
# autoscp -down srcpath (the same as autoscp -down srcpath .)
# autoscp -down srcpath dstpath (dstpath is based on $pwd)
# autoscp -up srcpath (the same as autoscp -up srcpath ~)
# autoscp -up srcpath dstpath (dstpath is based on ~ on the server)
#
set timeout 100
set cmd [lindex $argv0]
set option [lindex $argv 0]
set srcpath [lindex $argv 1]
set dstpath [lindex $argv 2]
#parse command number
switch -- $argc {
2 {
set dstpath .
}
3 {
}
default {
send_user "Usage:$cmd option srcpath \[dstpath\]\n"
exit
}
}
#parse command and do it.
if {$option=="-down"} {
spawn scp -r gyl@127.0.0.1:/home/gyl/$srcpath $dstpath
} else {
if {$option=="-up"} {
spawn scp -r $srcpath gyl@127.0.0.1:/home/gyl/$dstpath
} else {
send_user "bad arg:\"$option\"\n"
exit
}
}
#autofill infomation
expect "password:"
send "123456\n"
#exit
expect eof
autoscp -down srcpath #等价于autoscp -down srcpath .
autoscp -up srcpath dstpath #srcpath基于本地当前目录,dstpath基于服务器用户主目录
autoscp -up srcpath #等价于autoscp -up srcpath ~