linux下expect的使用

expect 使用
安装:
yum -y install expect


1,首行声明
2,控制台输出
3,设置日期变量$date
4,设置ip变量$local_ip 127.0.0.1
5,设置默认等待时间: 3000
#!/usr/bin/expect -f
set date [exec date "+%Y%m%d"]
set ip1 123.57.219.236
set timeout 3000

6,简单交互
spawn

send:用于向进程发送字符串
expect:从进程接收字符串
spawn:启动新的进程
interact:允许用户交互

等待输入"hi\n"
?
输出"hello word\n"
?

expect "hi\n"
send "you typed <$expect_out(buffer)>"
send "but I only expected <$expect_out(0,string)>"
当在标准输入中输入
test
hi
是,运行结果如下
you typed: test
hi
I only expect: hi




匹配到hi后,会输出"you said hi"
expect "hi" {send "You said hi"}


匹配到hi,hello,bye任意一个字符串时,执行相应的输出
expect {
"hi" { send "You said hi\n"}
"hello" { send "Hello yourself\n"}
"bye" { send "That was unexpected\n"}
}


这段代码的作用是登录到ftp服务器ftp ftp.uu.net上,并以二进制的方式下载服务器上的文件test.tar.gz。程序中有详细的注释。
set timeout -1
spawn ftp ftp.test.com      //打开新的进程,该进程用户连接远程ftp服务器.最后将控制权交给用户.
expect "Name"             //进程返回Name时
send "user\r"        //向进程输入anonymous\r
expect "Password:"        //进程返回Password:时
send "123456\r"    //向进程输入don@libes.com\r
expect "ftp> "            //进程返回ftp>时
send "binary\r"           //向进程输入binary\r
expect "ftp> "            //进程返回ftp>时
send "get test.tar.gz\r"  //向进程输入get test.tar.gz\r
interact
ssh免密码登录:123.57.219.236,密码:123456:
spawn ssh -p10022 root@123.57.219.236
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "123456\n\r"}
}
interact


执行236上指定目录的脚本,可以适配第一次连接:


spawn ssh -p 10022  rsync@$ip1 "expect /data/software/bak/rsync_2_48.sh"
expect {
      "yes/no" { send "yes\r";exp_continue}
      "$ip1's password:" { send "pwd@123\n\r"}
      }
expect eof
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 分支


#!/usr/bin/expect
set test [lindex $argv 0]
if { "$test" == "apple" } {
        puts "$test"
} else  {
        puts "not apple"
}
for 循环结构
第一种


foreach number {
1
2
3thread
4third
} {
        puts "$number"
}


第二种


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


while  循环结构


set i 1
while {$i<4} {
        puts "$i"
        incr i
}


4 函数定义


proc test {} {
        puts "ok"
}
test




5. 结尾加 interact
  执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。如果没有这一句登录完成后会退出,而不是留在远程终端上。如果你只是登录过去执行

然后在shell脚本中调用即可:

#!/bin/bash
expect /root/shell/login.exp agrv1 agrv2



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值