利用shell和expect结合实现后台scp大文件

版权声明:本文原创,转载请注明出处。 https://blog.csdn.net/weixin_39004901/article/details/89208823

今天想要扩机房传输一个33G的压缩文件,传输速度只有1.7M/s,如果用scp,需要长时间保持终端不关闭,且网络不能断。
为了把scp放在后台运行,并自动输入远端用户密码,最初是想单纯写个expect的脚本,但是发现expect脚本没办法和nohup &一起跑,所以将shell和expect结合起来,写了如下脚本:

cat scp_auto.sh
#!/bin/bash
#usage:sh scp_auto.sh /backup/mysql_full_backup/xxx.tar.gz bmviewer@remote_ip:/tmp
#description:prevents large file transfer disruption
#caiyuxing

#the direct path of file you wanna scp,for example,/backup/mysql_full_backup/mysql_full_2019-04-11_01-00-01.tar.gz
local_file=$1
#the target path,for example,[email protected]:/tmp
remote_path=$2

expect <<-EOF
spawn scp $local_file $remote_path
expect "*password:"
send "sam123\r"
expect eof;
EOF
exit

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

cat scp_auto.sh
#!/bin/bash
#usage:sh scp_auto.sh /backup/mysql_full_backup/xxx.tar.gz bmviewer@remote_ip:/tmp
#description:prevents large file transfer disruption
#caiyuxing

#the direct path of file you wanna scp,for example,/backup/mysql_full_backup/mysql_full_2019-04-11_01-00-01.tar.gz
local_file=$1
#the target path,for example,[email protected]:/tmp
remote_path=$2

expect <<-EOF
set timeout 28800
spawn scp $local_file $remote_path
expect "*password:"
send "sam123\r"
expect eof;
EOF
exit

运行脚本:
nohup sh scp_auto.sh /backup/mysql_full_backup/mysql_full_2019-04-11_01-00-01.tar.gz [email protected]:/tmp

猜你喜欢

转载自blog.csdn.net/weixin_39004901/article/details/89208823