---
title: "ActiveTCL的Expect学习笔记（自动收邮件）"
author: "igaozh"
date: "2012-12-22T18:08:21Z"
tags: []
categories: ["编程语言"]
slug: "activetcl-expect"
draft: false
lastmod: "2012-12-25T21:21:00Z"
id: 1752426
url: "https://igaozh.iteye.com/blog/1752426"
---

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](http://heylinux.com/archives/1043.html)

 

expect和autoexpect实现自动交互学习笔记

[http://www.xmydlinux.org/201109/607.html](http://www.xmydlinux.org/201109/607.html)

 

$expect\_out(buffer)包含send的数据

[http://blog.csdn.net/bonny95/article/details/5755541](http://blog.csdn.net/bonny95/article/details/5755541)

 

如何捕获expect中spawn进程的返回值：

[http://tsecer.blog.163.com/blog/static/150181720129211035494/](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
}
```