读书人

ActiveTCL的Expect学习札记(自动收邮

发布时间: 2012-12-29 10:28:09 作者: rapoo

ActiveTCL的Expect学习笔记(自动收邮件)

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

?

推荐读物:

http://heylinux.com/archives/1043.html

http://www.xmydlinux.org/201109/607.html

?

最后给出一个自动连接pop.126.com服务器的例子:

?

package require Expectset hostname "pop.126.com"set username "abc"set password "xxx"puts stdout "Connecting to $hostname ."spawn telnet $hostname 110expect -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}

读书人网 >编程

热点推荐