expect实现scp远程复制文件 spawn

expect实现scp远程复制文件 spawn

rpm -qa | grep expect

sudo apt-get install expect
ls /usr/bin | grep expect
sudo apt-get install tcl tk expect
sudo apt show expect

Expect是一个用来实现自动交互功能的软件套件。
使用Expect可以模拟手工交互的过程,实现自动与远端程序的交互。例如当执行ssh命令连接服务器时,需要手动输入密码,如果采用Expect,就可以自动交互,无需再人工手动输入密码了。

whereis expect
expect: /usr/bin/expect /usr/share/man/man1/expect.1.gz

cat /opt/shell/expect_scp.sh
#!/bin/bash
expect << EOF
set timeout -1
spawn bash -c “scp -pr /home/* [email protected]:/home/”
expect {
“yes/no” {send “yes\r”;exp_continue}
“password” {send “123456\r”;}
}
expect eof
EOF

密码中 有特殊字符的

需要转义一下
send每个特殊字符前面都加上\就可以了

需要等待代码执行完

expect  "*100%*"

1、expect基本命令了解

spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间

标题3、利用shell和expect结合实现后台scp大文件

//脚本可以正常运行,但是每次都传了18M就自动停止了。后来了解到,expect有默认的命令运行时限,超时后会自动停止运行,解决方法是加入set timeout 28800(超时时间为8小时),所以完整脚本如下:
cat /opt/shell/expect_scp.sh

#!/bin/bash
expect << EOF
set timeout 28800
spawn bash -c “scp -pr /home/* [email protected]:/home/”
expect {
“yes/no” {send “yes\r”;exp_continue}
“password” {send “123456\r”;}
}
expect eof
exit
EOF

猜你喜欢

转载自blog.csdn.net/wowocpp/article/details/131006707