1.默认高版本的ActiveTCL不包含Expect,安装方法(Expect不能写成expect):
teacup install Expect
2.使用Expect写脚本必须要在脚本中包含:
package require Expect
3.执行Expect脚本:
tclsh xxx
4.在调用exp_send自动发送信息的时候,内容最后使用'\r'或'\n'(若使用'\r\n'或'\n\r'结尾将出现逻辑问题)如:
exp_send "user $username\r"
5.调用exp_send_user给自己回显信息的时候,内容最后使用'\n',而不要使用'\r',如:
exp_send_user "could not connect\n"
6.正则表达式建议使用大括号包裹(使用引号包裹会无法识别'[]'等),如:
expect -re {^\+ OK [0-9]+ [0-9]+} {send "xxx\r"}
7.善于使用exp_sleep,在很多交互过程中,一个命令远端可能进行两次或更多次的数据发送,此时就需要程序执行exp_sleep来等待数据的到来,以便回显,如
exp_sleep 1
8.正则捕获返回结果:
expect -re "([0-9]*)([a-zA-Z]*)"
send_user "num is $expect_out(1,string), string is $expect_out(1,string)"
这里[0-9]*表示一个或多个数字,[a-zA-Z]*表示多个字母。()用于分组,他们分别存放在$expect_out(1,string)和$expect_out(2,string)中。
9.日志记录log_file,如:
log_file -noappend result.log
10.在远端执行的命令不要太长,建议在40个字符内(过长的命令不会在远端执行)
11.字符串比较方法如下,'=='只能用于比较整数,比较时字符串常量要使用双引号包裹(使用单引号会异常结果):
set ispv [string equal $expect_out(5,string) "pv"]
12.if...else...语句中注意在关键字(if和else)与'{'、'}'之间需要空格,如果缺少就会报错误:
extra characters after close-brace
推荐读物:
通过expect脚本远程批量管理服务器
http://heylinux.com/archives/1043.html
expect和autoexpect实现自动交互学习笔记
http://www.xmydlinux.org/201109/607.html
$expect_out(buffer)包含send的数据
http://blog.csdn.net/bonny95/article/details/5755541
如何捕获expect中spawn进程的返回值:
http://tsecer.blog.163.com/blog/static/150181720129211035494/
最后给出一个自动连接pop.126.com服务器的例子:
package require Expect set hostname "pop.126.com" set username "abc" set password "xxx" puts stdout "Connecting to $hostname ." spawn telnet $hostname 110 expect -re ".*OK.*" { exp_send "user $username\r" } eof { exp_send_user "could not connect\n" } expect -re ".*OK.*" { exp_send "pass 280755834\r" } expect -re ".*OK.*" { exp_send "list\r" } exp_sleep 1#sleep的目的是回显list命令的返回结果 exp_send "quit\r" exp_sleep 1#sleep的目的是回显quit命令和服务的返回结果:'quit','+OK core mail' expect -re ".*OK.*" { exp_send_user "quit success\n" exp_sleep 3 }