分类:
2011-12-21 22:38:54
原文地址:Expect实现自动交互 作者:badb0y
一、如何获取Expect支持
Expect在centos中需要安装Tcl和expect这2个rpm包。Expect依赖于Tcl。
二、Expect基本语法
expect 用于读取希望看到的输出,和shell中read差不多
-exact参数为验证一切输入参数,包括 \n \r \t 等字符
send 发送命令,代替手动输入
spawn 产卵,初始化expect脚本的第一个命令,用于产生一个开始记录的点
if while for 循环全部使用花括号作为分隔,其余和shell一致
puts 等同于 echo
设置位置变量 set number [lindex $argv 0]
【例如:】
for {set number=1} {$ number <= 100} { incr number +1}
{
puts “The number is $ number”
}
三、自动录制
以录制dell硬件检查脚本为例:
autoexpect sh delldset_v2.1.0.112_A00.bin
录制脚本,跟随提示输入相关选项
生成文件是script.exp
[root@localhost ~]# cat script.exp
#!/usr/bin/expect -f # Expect脚本幻数,用于引用expect变量和函数
#
# This Expect script was generated by autoexpect on Fri Nov 25 20:21:59 2011
# Expect and autoexpect were both written by Don Libes, NIST.
#
# Note that autoexpect does not guarantee a working script. It
# necessarily has to guess about certain things. Two reasons a script
# might fail are:
#
# 1) timing - A surprising number of programs (rn, ksh, zsh, telnet,
# etc.) and devices discard or ignore keystrokes that arrive "too
# quickly" after prompts. If you find your new script hanging up at
# one spot, try adding a short sleep just before the previous send.
# Setting "force_conservative" to 1 (see below) makes Expect do this
# automatically - pausing briefly before sending each character. This
# pacifies every program I know of. The -c flag makes the script do
# this in the first place. The -C flag allows you to define a
# character to toggle this mode off and on.
set force_conservative 0 ;# set to 1 to force conservative mode even if
;# script wasn't run conservatively originally
if {$force_conservative} {
set send_slow {1 .1}
proc send {ignore arg} {
sleep .1
exp_send -s -- $arg
}
}
##此段的含义是避免脚本运行过快错过输入,将force_conservative设置为1,会使发送send前停顿一会儿
#
# 2) differing output - Some programs produce different output each time
# they run. The "date" command is an obvious example. Another is
# ftp, if it produces throughput statistics at the end of a file
# transfer. If this causes a problem, delete these patterns or replace
# them with wildcards. An alternative is to use the -p flag (for
# "prompt") which makes Expect only look for the last line of output
# (i.e., the prompt). The -P flag allows you to define a character to
# toggle this mode off and on.
#
# Read the man page for more info.
#
# -Don
set timeout -1 ##设置为永不超时
spawn sh delldset_v2.1.0.112_A00.bin ##开始录制
match_max 100000 ##设置缓冲区大小,单位:字节。
expect -exact "[H[J[?1h\rDELL SOFTWARE LICENSE AGREEMENT\r
\r
This is a legal agreement between you, the user, and Dell Products, L.P (\"Dell\"). This agreement covers all software that is distributed with the Dell product, for which there is no separate license agreement between you and the manufacturer or owner of the software (collectively the \"Software\"). By opening or breaking the seal on the Software packet(s), installing or downloading the Software, or using the Software that has been preloaded or is embedded in your product, you agree to be bound by the terms of this agreement. If you do not agree to these terms, promptly return all Software items (disks, written materials, and packaging) and delete any preloaded or embedded Software. \r
\r
You may use one copy of the Software on only one computer at a time. If you have multiple licenses for the Software, you may use as many copies at any time as you have licenses. \"Use\" means loading the Software in temporary memory or permanent storage on the computer. Installation on a network server solely for distribution to other computers is not \"use\" if (but only if) you have a separate license for each computer to which the Software is distributed. You must ensure that the number of persons using the Software installed on a network server does not exceed the number of licenses that you have. If the number of users of Software installed on a network server will exceed the number of licenses, you must purchase additional licenses until the number of licenses equals the number of users before allowing additional users to use the Software. If you are a commercial customer of Dell or a Dell affiliate, you hereby grant Dell, or an agent selected by Dell, the right to perform an audit of your use of the Software during normal business hours, you agree to cooperate with Dell in such audit, and you agree to provide Dell with all records reasonably related to your use of the Software. The audit will be limited to verification of your compliance with the terms of this agreement. \r
\r
The Software is protected by United States copyright laws and international treaties. You may make one copy of the Software solely for backup or archival purposes or transfer it to a single hard disk provided you keep the original solely for backup or archival purposes. You may not rent or lease the Software or copy the written materials accompanying the Software, but you may transfer the Software and all accompanying materials on a permanent basis in conjunction with a transfer of the Dell product if you retain no copies and the recipient agrees to the terms hereof. Any transfer must include the most recent update and all prior versions. You may not reverse engineer, decompile or disassemble the Software. If the package accompanying your computer contains compact discs, 3.5\" and/or 5.25\" disks, you may use only the disks appropriate for your computer. You may not use the disks on another computer or network, or loan, rent, lease, or transfer them to another user except as permitted by this agreement.\r
\r
All open source code used by the Software is provided \"as is\" without any modification. You may request only the open source code used by the Software on physical media for a fee, but not the Software itself.\r
\r
LIMITED WARRANTY\r
\r
Dell warrants that the Software disks will be free from defects in materials and workmanship under normal use for ninety (90) days from the date you receive them. This warranty is limited to you and is not transferable. Any implied warranties are limited to ninety (90) days from the date you receive the Software. Some jurisdictions do not allow limits on the duration of an implied warranty, so this limitation may not apply to you. The entire liability of Dell and its suppliers, and your exclusive remedy, shall be (a) return of the price paid for the Software or (b) replacement of any disk not meeting this warranty that is sent with a return authorization number to Dell, at your cost and risk. This limited warranty is void if any disk damage has resulted from accident, abuse, misapplication, or service or modification by someone other than Dell. Any replacement disk is warranted for the remaining original warranty period or thirty (30) days, whichever is longer. \r
\r
Dell does NOT warrant that the functions of the Software will meet your requirements or that operation of the Software will be uninterrupted or error free. You assume responsibility for selecting the Software to achieve your intended results and for the use and results obtained from the Software.\r
\r
DELL, ON BEHALF OF ITSELF AND ITS SUPPLIERS, DISCLAIMS ALL OTHER WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, FOR THE SOFTWARE AND ALL ACCOMPANYING WRITTEN MATERIALS. This limited warranty gives you specific legal rights; you may have others, which vary from jurisdiction to jurisdiction.\r
\r
IN NO EVENT SHALL DELL OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING OUT OF USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Because some jurisdictions do not allow an exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.\r
\r
[7mDell License (66%): Press spacebar to view next page, 'q' to proceed[m[K" ##底纹灰色显示
send -- "q"
expect -exact "\r[K[?1l\r
Do you accept the terms of this license? (y/n): "
send -- "y"
expect -exact "\r
[H[J[1mDell System E-Support Tool (DSET) Options:[0m\r
\r
\r
Choose an option:\r
\r
[1m 1) Read DSET Release Notes First[0m\r ##高亮加粗显示
Show latest information concerning features and known issues\r
\r
[1m 2) Create DSET Report Only[0m\r
Creates a DSET report and saves it to user's home directory\r
\r
[1m 3) Clear ESM Hardware Log Only[0m\r
Only clears the ESM Hardware Log contents\r
\r
[1m 4) Install/Upgrade DSET Application[0m\r
Permanently installs or upgrades the DSET application for repeat use\r
\r
Enter option (1-4) or 'q' to quit: "
send -- "2"
expect -exact "\r
\r
[1mYour Information:[0m\r
Please enter your company name and e-mail address.\r
This information is optional but will help Dell Technical Support\r
when analyzing your report.\r
\r
Company Name: "
send -- "SINA\r"
expect -exact "SINA\r
Your E-mail: "
send -- "wangliang4@staff.sina.com.cn\r"
expect -exact "wangliang4@staff.sina.com.cn\r
\r
Preparing DSET components to create a report. One moment ...\r
\r
\r
[H[JChoose Report options:\r
\r
[1m Skip collecting info for all hardware categories(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Skip collecting info for all storage categories(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Skip collecting info for all software categories(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Skip collecting any non-Linux log files(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Append report filename with timestamp(y/n): [0m"
send -- "y\r"
expect -exact "y\r
[1m Collect various advanced logs(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Do you need to store in a different location(y/n): [0m"
send -- "n\r"
expect eof
四、精简生成后的脚本为手写体
自动生成中得脚本有一些不可读的字符,并且因为每次屏幕显示的字符不一样,可能包含系统时间或者分屏帮助等等会经常变化的字符,故需要精简为易于执行的普通格式。
1、第一次精简
精简了很多大段的提示,因为大段文字,每次分屏显示不同,做法只有2中,要么全部写全,要么全部删除或者用通配符代表上下文。
但下列代码仍包含很多特殊字符,和精确的exact表示格式,需要再次精简为普通格式。精确格式的容错能力差。
set timeout -1
spawn sh delldset_v2.1.0.112_A00.bin
match_max 100000
send -- "q" # 精简了帮助,直接输入q跳过
send -- "y" # 此处精简了读声明,直接输入y跳过
send -- "2" # 此处精简了菜单,直接输入2选择建立文档
send -- "SINA\r" #此处精简了公司名提示
expect -exact "SINA\r
Your E-mail: "
send -- "wangliang4@staff.sina.com.cn\r"
expect -exact "wangliang4@staff.sina.com.cn\r
\r
Preparing DSET components to create a report. One moment ...\r
\r
\r
[H[JChoose Report options:\r
\r
[1m Skip collecting info for all hardware categories(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Skip collecting info for all storage categories(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Skip collecting info for all software categories(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Skip collecting any non-Linux log files(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Append report filename with timestamp(y/n): [0m"
send -- "y\r"
expect -exact "y\r
[1m Collect various advanced logs(y/n): [0m"
send -- "n\r"
expect -exact "n\r
[1m Do you need to store in a different location(y/n): [0m"
send -- "n\r"
expect eof
2、第二次精简
精简了所有非主要的提示语句,去掉了字符字数限制,精简了所有特殊字符。
set timeout -1
spawn sh delldset_v2.1.0.112_A00.bin
send "q"
send "y"
send "2"
send "SINA\r"
send "wanagliang4@staff.sina.com.cn\r "
expect "*Skip collecting info for all hardware categories(y/n)*"
send "n\r"
expect "*Skip collecting info for all storage categories(y/n)*"
send "n\r"
expect "*Skip collecting info for all software categories(y/n)*"
send "n\r"
expect "*Skip collecting any non-Linux log files(y/n)*"
send "n\r"
expect "*Append report filename with timestamp(y/n)*"
send "y\r"
expect "*Collect various advanced logs(y/n)*"
send "n\r"
expect "*Do you need to store in a different location(y/n)*"
send "n\r"
expect eof
五、脚本复杂化
上述脚本不一定能执行通过,原因就是中间过程输入和输出交互的太快,脚本来不及反映导致没等返回就又再次输入了内容。故精简的同时也需要将脚本复杂化
1、加入更多的提示语句让脚本连续化
set timeout -1
spawn sh delldset_v2.1.0.112_A00.bin
send "q"
send "y"
send "2"
expect "*Company Name*" ##加入了公司名提示
send "SINA\r"
expect "*Your E-mail*" ##加入了email提示
send "wangliang4@staff.sina.com.cn\r "
expect *Skip collecting info for all hardware categories(y/n)*"
send "n\r "
expect "*Skip collecting info for all storage categories(y/n)*"
send "n\r "
expect "*Skip collecting info for all software categories(y/n)*"
send "n\r"
expect "*Skip collecting any non-Linux log files(y/n*"
send "n\r"
expect "*Append report filename with timestamp(y/n*"
send "y\r"
expect "*Collect various advanced logs(y/n)*"
send "n\r"
expect "*Do you need to store in a different location(y/n)*"
send "n\r"
expect eof
再次复杂化加入判断分支和变量参数化
此脚本只能在系统干净的情况下运行1次,当你运行过一次时,之前的参数会影响运行的过程。
系统提示
A version of DSET is already installed!
Upgrade it and then clear the log? (y/n): y
Preparing DSET components to clear the log. One moment ...
故再次复杂化,加入判断分支,并一并将输入的email参数化。完成全部脚本
#!/usr/bin/expect -f
#rsync script for delldest
set user [lindex $argv 0]
set timeout -1
if { $argc!=1 } {
puts stderr "NOTICE: need a USERNAME"
puts "USEAGE: checkDisk.tcl \[yourname\]"
puts "EXAMPLE: checkDisk.tcl wangliang4"
exit 1
}
spawn ./delldset_v2.1.0.112_A00.bin
send "q"
send "y"
expect "*quit:"
send "2"
expect {
"*Upgrade it and then create a report?*"
{
send "y\r"
}
"*Company Name*"
{
send "SINA\r"
expect "*Your E-mail*"
send "$user@staff.sina.com.cn\r"
}
}
expect "*Skip collecting info for all hardware categories*"
send "n\r"
expect "*Skip collecting info for all storage categories*"
send "n\r"
expect "*Skip collecting info for all software categories*"
send "n\r"
expect "*Skip collecting any non-Linux log files*"
send "n\r"
expect "*Append report filename with timestamp*"
send "y\r"
expect "*Collect various advanced logs*"
send "n\r"
expect "*Do you need to store in a different location*"
send "n\r"
expect eof
转:http://blog.sina.com.cn/s/blog_502c8cc401011vff.html