一、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脚本中对字符转义只需要一个反斜杠。