ex pect 学习笔记及实例详解1.ex pect 是基于 tcl演变而来的,所以很多语法和 tcl类似,基本的语法如下所示:1.1首行加上/usr/bin/ex pect1.2spawn:后面加上需要执行的 shell命令,比如说 spawnsudotouchtestfile1.3ex pect: 只有 spawn执行的命令结果才会被 ex pect 捕捉到,因为 spawn会启动一个进程,只有这个进程的相关信息才会被捕捉到,主要包括:标准输入的提示信息,eof和 timeout。1.4send和 send_user:send会将 ex pect 脚本中需要的信息发送给 spawn启动的那个进程,而 send_user只是回显用户发出的信息,类似于 shell中的 echo而已。2.一个小例子,用于 linux下账户的建立:filename:account.sh,可以使用./account.shnewaccout来执行;1#!/usr/bin/ex pect23set passwd"mypasswd"4set timeout6056if{$argc!=1}{7send"usage./account.sh\$newaccount\n"8ex it9 }1011 set user [lindex $argv [expr $argc-1]]1213 spawn sudo useradd -s /bin/bash -g mygroup -m $user1415 expect {16"assword" {17send_user "sudo now\n"18send "$passwd\n"19exp_continue20}21eof22{23send_user "eof\n"24}25 }2627 spawn sudo passwd $user28 expect {29"assword" {30send "$passwd\n"31exp_continue32}33eof34{35send_user "eof"36}37 }3839 spawn sudo smbpasswd -a $user40 expect {41"assword" {42send "$passwd\n"43exp_continue44}45eof46{47send_user "eof"48}49 }3. 注意点:第3 行:对变量赋值的方法;第4 行:默认情况下,timeout 是 10 秒;第6 行:参数的数目可以用$argc 得到;第11 行:参数存在$argv 当中,比如取第一个参数就是[lindex $argv 0];并且如果需要计算的话必须用 expr,如计算 2-1,则必须用[expr 2-1];第 13 行 : 用 spawn 来 执 行 一 条 shell 命 令 , shell 命 令 根 据 具 体 情 况 可 自 行 调 整 ;有 文 章 说 sudo 要 加 -S, 经 过 实 际 测 试 , 无 需 加 -S 亦 可 ;第 15 行 : 一 般 情 况 下 , 如 果 连 续 做 两 个 expect, 那 么 实 际 上 是 串 行 执 行 的 , 用例 子 中 的 结 构 则 是 并 行 执 行 的 , 主 要 是 看 匹 配 到 了 哪 一 个 ; 在 这 个 例 子 中 , 如 ...