您的位置:首页 > 其它

expect语法

2015-12-31 12:06 295 查看
沙河西ftp上传,使用了expect语言的脚本。

一 Background:

系统管理员在工作中经常会遇到这样的问题,需要实现一个自动交互的工具,这个工具可以自动Telnet或者Ftp到指定的服务器上,成功login之后自动执行一些命令来完成所需的工作。

  当然,有很多编程语言可以去解决此类问题,比如用C、Perl、或者Expect。

  显然,尽管C是无所不能的,但是解决此类问题还是比较困难,除非你熟悉Telnet或者Ftp协议。

  曾经见过别人用C实现了一个简单的Telnet客户端协议的程序,可以在这个程序加入自己的代码来捕获服务端的输出,根据这些输出来发送适当的指令来进行远程控制。

  使用Perl一样可以实现这样的功能,然而,Expect做的更出色,而且除支持Unix/Linux平台外,它还支持Windows平台,它就是为系统管理和软件测试方面的自动交互类需求而产生的
二 What is expect :
  Expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。

  Expect的作者Don Libes在1990年开始编写Expect时对Expect做有如下定义:

  Expect是一个用来实现自动交互功能的软件套件(Expect [is a] software suite for automating interactive tools)。

三 expect 语法:
1 定义变量
[root@localhost expect]# cat 1.exp
#!/usr/bin/expect
set test 123 #自定义变量
set commd [exec ls] #调用系统命令赋值
set ip [lindex $argv 0] # 参数赋值
puts "test is $test"
puts "$commd"
puts "ip is $ip"

[root@localhost expect]# ./1.exp 10.1.1.1
test is 123
1.exp
2.exp
ip is 10.1.1.1

[root@localhost expect]# cat 1.exp
#!/usr/bin/expect
set nb1 [lindex $argv 0] #执行的第一个参数
set nb2 [lindex $argv 1] # 执行第二个参数
puts "$argc" # 参数数量
puts "$argv0" # 程序名字
puts "$nb1"
puts "$nb2"
[root@localhost expect]# ./1.exp abc def
2
./1.exp
abc
def
=======================
2 switch 分支结构
[root@localhost expect]# cat 2.exp
#!/usr/bin/expect
set color [lindex $argv 0]
switch $color {
apple {
puts "apple is blue"
}
banana {
puts "banana is yellow "
}

}
[root@localhost expect]# ./2.exp apple
apple is blue
[root@localhost expect]# ./2.exp banana
banana is yellow

if 分支
[root@localhost expect]# cat 3.exp
#!/usr/bin/expect
set test [lindex $argv 0]
if { "$test" == "apple" } {
puts "$test"
} else {
puts "not apple"
}
[root@localhost expect]# ./3.exp apple
apple
[root@localhost expect]# ./3.exp banana
not apple
=========================
for 循环结构
第一种
[root@localhost expect]# cat 5.exp
#!/usr/bin/expect
foreach number {
1
2
3
4
} {

puts "$number"
}
[root@localhost expect]# ./5.exp
1
2
3
4

第二种
[root@localhost expect]# cat 5.exp
#!/usr/bin/expect
for {set i 0} {$i<4} {incr i} {
puts "$i"
}
[root@localhost expect]# ./5.exp
0
1
2
3

while 循环结构
[root@localhost expect]# cat 5.exp
#!/usr/bin/expect
set i 1
while {$i<4} {
puts "$i"
incr i
}
[root@localhost expect]# ./5.exp
1
2
3

========================
函数定义
[root@localhost expect]# cat 6.exp
#!/usr/bin/expect
proc test {} {
puts "ok"
}
test
[root@localhost expect]# ./6.exp
ok
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: