例1:下面是一个telnet到指定的远程机器上自动执行命令的Expect脚本,该脚本运行时的输出如下:
# /usr/bin/expect sample_login.exp root 111111
spawn telnet 10.13.32.30 7001
Trying 10.13.32.30...
Connected to 10.13.32.30.
Escape character is '^]'.
accho console login: root
Password:
Last login: Sat Nov 13 17:01:37 on console
Sun Microsystems Inc. SunOS 5.9 May 2004
#
Login Successfully...
# uname -p
sparc
# ifconfig -a
lo0: flags=2001000849 mtu 8232 index 1
inet 127.0.0.1 netmask ff000000
eri0: flags=1000843 mtu 1500 index 2
inet 10.13.22.23 netmask ffffff00 broadcast 10.13.22.255
ether 0:3:ba:4e:4a:aa
# exit
accho console login:
Finished...
下面是该脚本的源代码:
# vi sample_login.exp:
proc do_console_login {login pass} {
set timeout 5
set done 1
set timeout_case 0
while ($done) {
expect {
"console login:" { send "$login\n" }
"Password:" { send "$pass\n" }
"#" {
set done 0
send_user "\n\nLogin Successfully...\n\n"
}
timeout {
switch -- $timeout_case {
0 { send "\n" }
1 {
send_user "Send a return...\n"
send "\n"
}
2 {
puts stderr "Login time out...\n"
exit 1
}
}
incr timeout_case
}
}
}
}
proc do_exec_cmd {} {
set timeout 5
send "\n"
expect "#"
send "uname -p\n"
expect "#"
send "ifconfig -a\n"
expect "#"
send "exit\n"
expect "login:"
send_user "\n\nFinished...\n\n"
}
if {$argc<2} {
puts stderr "Usage: $argv0 login passwaord.\n "
exit 1
}
set LOGIN [lindex $argv 0]
set PASS [lindex $argv 1]
spawn telnet 10.13.32.30 7001
do_console_login $LOGIN $PASS
do_exec_cmd
close
exit 0
上面的脚本只是一个示例,实际工作中,只需要重新实现do_exec_cmd函数就可以解决类似问题了。
在例1中,还可以学习到以下Tcl的语法:
1. 命令行参数
$argc,$argv 0,$argv 1 ... $argv n
if {$argc<2} {
puts stderr "Usage: $argv0 login passwaord.\n "
exit 1
}
2. 输入输出
puts stderr "Usage: $argv0 login passwaord.\n "
3. 嵌套命令
set LOGIN [lindex $argv 0]
set PASS [lindex $argv 1]
4. 命令调用
spawn telnet 10.13.32.30 7001
5. 函数定义和调用
proc do_console_login {login pass} {
..............
}
6. 变量赋值
set done 1
7. 循环
while ($done) {
................
}
8. 条件分支Switch
switch -- $timeout_case {
0 {
...............
}
1 {
...............
}
2 {
...............
}
}
9. 运算
incr timeout_case
此外,还可以看到 Expect的以下命令:
send
expect
send_user
可以通过-d参数调试Expect脚本:
# /usr/bin/expect -d sample_login.exp root 111111
......调试输出和程序输出.......
阅读(2098) | 评论(0) | 转发(0) |