您的位置:首页 > 其它

expect的使用

2016-03-31 10:47 162 查看
下载与安装:

yum -y install expect 或参考 http://blog.csdn.net/xiaofei0859/article/details/6047207
1,使用变量

set date [exec date "+%Y-%m-%d"]
$date 

set commd [exec ls]   #调用系统命令赋值

set ip [lindex $argv 0] #   参数赋值  ./1.exp xxx 调用

puts "ip is $ip" #控制台输出

2,获取执行参数

set nb1 [lindex $argv 0]    #执行的第一个参数

set nb2 [lindex $argv 1]    # 执行第二个参数

puts "$argc"    # 参数数量

puts "$argv0"    # 程序名字

3,逻辑判断

switch  分支结构

set color  [lindex $argv 0]

switch  $color  {

        apple {

                puts "apple is blue"

        }

        banana {

                puts "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"

}

for 循环结构

第一种

[root@localhost expect]# cat 5.exp

#!/usr/bin/expect

foreach number {

1

2

3

4

} {

        puts "$number"

}

第二种

[root@localhost expect]# cat 5.exp

#!/usr/bin/expect

for {set i 0} {$i<4} {incr i} {

        puts "$i"

}

while  循环结构

[root@localhost expect]# cat 5.exp

#!/usr/bin/expect

set i 1

while {$i<4} {

        puts "$i"

        incr i

}

4 函数定义

[root@localhost expect]# cat 6.exp

#!/usr/bin/expect

proc test {} {

        puts "ok"

}

test

5,返回条件判断

  expect {

      "yes/no" { send "yes\r";exp_continue}

      "assword" { send "${pw}\r"}

      }

6. 结尾加 [interact] 

  执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。如果没有这一句登录完成后会退出,而不是留在远程终端上。如果你只是登录过去执行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: