Linux expect

一、expect

expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。

1.1 示例1:使用expect自动上传文件到sftp服务器

#!/usr/bin/expect 

set sftp_user [lindex $argv 0]
set sftp_pwd [lindex $argv 1]
set targetPath [lindex $argv 2]
set sftp_port [lindex $argv 3]
set destFile /test

set timeout 300
spawn sftp -oPort=$sftp_port $sftp_user@$sftp_host:$targetPath
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$sftp_pwd\r" }
}
send "$sftp_pwd\r"
expect "sftp>"
send "put $destFile\r"
expect "sftp>"
send "exit\n"
expect eof
EOF

1.2 示例2:在shell中嵌套expect

#!/bin/bash

sftp_user=root
sftp_pwd=root
targetPath=127.0.0.1
sftp_port=22
destFile=/test

/usr/bin/expect <<-EOF
#!/usr/bin/expect
set timeout 300
spawn sftp -oPort=$sftp_port $sftp_user@$sftp_host:$targetPath
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$sftp_pwd\r" }
}
send "$sftp_pwd\r"
expect "sftp>"
send "put $destFile\r"
expect "sftp>"
send "exit\n"
expect eof
EOF

1.3 参数说明

  • set 可以设置超时,也可以设置变量
  • spawn 执行一个命令
  • timeout expect超时等待时间,默认10S,-1表示永不退出
  • log_user 是否显示脚本输出信息 1代表显示,0代表不显示
  • log_file 记录交互信息到指定文件;
  • expect 匹配输出的内容
  • expect{…}: 匹配多次输出的内容
  • exp_continue 继续执行下面匹配
  • send 发送指定内容
  • interact:交互后不退出远程终端
  • $argc:统计位置参数数量
  • [lindex $argv 0]:脚本后第一个参数,类似于shell中$1,以此类推
  • \r:可以理解为回车

1.4 expect常见问题
1.4.1expect脚本中source命令不起作用?

shell脚本中嵌套expect脚本,再编写source命令即可正常使用

1.4.2、shell嵌套expect脚本中$expect_out(1,string)无法获得匹配字符串?

单纯使用expect脚本即可正常获取

1.4.3、shell嵌套expect脚本中对字符转义需要三个反斜杠,expect脚本中对字符转义只需要一个反斜杠。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书香水墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值