Bash 远程拷贝文件的函数

需安装 expect 才能正常使用。

1
yum install -y expect;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env bash
#远程拷贝文件
set -e;

#拷贝远程文件到本地
EXPECT_CP_R(){
local EXUSR=${1}
local EXHOST=${2}
local EXPWD=${3}
local R_FILE=${4}
local L_FILE=${5}

expect -c "
set timeout 300
spawn scp -qr ${EXUSR}@${EXHOST}:${R_FILE} ${L_FILE}
expect {
\"not known\" {send_user \"[exec echo -e Erro:Host not known\n];exit\"}
\"Connection refused\" {send_user \"[exec echo -e Erro:Connection refused\n];exit\"}
\"(yes/no)?\" {send \"yes\r\";exp_continue}
\"password:\" {send \"${EXPWD}\r\";exp_continue}
\"Permission denied\" {send_user \"[exec echo -e Erro:Wrong passwd\n];exit\"}
\"]*\" {send \"\r\"}
\">*\" {send \"\r\"}
}
"
}

#拷贝本地文件到远程
EXPECT_CP_L(){
local EXUSR=${1}
local EXHOST=${2}
local EXPWD=${3}
local L_FILE=${4}
local R_FILE=${5}

expect -c "
set timeout 300
spawn scp -qr ${L_FILE} ${EXUSR}@${EXHOST}:${R_FILE}
expect {
\"not known\" {send_user \"[exec echo -e Erro:Host not known\n];exit\"}
\"Connection refused\" {send_user \"[exec echo -e Erro:Connection refused\n];exit\"}
\"(yes/no)?\" {send \"yes\r\";exp_continue}
\"password:\" {send \"${EXPWD}\r\";exp_continue}
\"Permission denied\" {send_user \"[exec echo -e Erro:Wrong passwd\n];exit\"}
\"]*\" {send \"\r\"}
\">*\" {send \"\r\"}
}
"
}