Linux Sftp上传下载文件

本文遵循BY-SA版权协议,转载请附上原文出处链接。


本文作者: 黑伴白

本文链接: http://heibanbai.com.cn/posts/7971c3cf/

说明

通过Linux的sftp命令,实现获取或推送数据文件

脚本源码

具体如下:

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/bin/bash

##############################################################
# Date : 2020-07-28
# AUTHOR: zhaoty
# Desc : sftp获取或推送数据文件
##############################################################

#获取脚本名称
shName=`basename $0`

#接收参数
localPath=$1
remotePath=$2
serverIp=$3
sftpUser=$4
sftpPass=$5
cmd=$6

#当前系统日期-yyyymmdd
sysDate=`date +"%Y%m%d"`

#定义日志文件路径和日志文件名
logPath=/home/zhaoty/data/log/sftpgpfile/${sysDate}
logFile=${logPath}/sftpgpfile.log

#定义日志函数
Log()
{
createTime=`date +"%Y-%m-%d %H:%M:%S"`
echo "[${createTime}] $*" |tee -a ${logFile} 2>/dev/null
}

#定义检查创建目录函数
CheckDir()
{
if [ ! -d $1 ]; then
mkdir_log=` mkdir -p -m 775 $1 `
if [ $? -ne 0 ]; then
echo "[ERROR]: Directory [$1] create fail, please check..."
exit 1
fi
fi
}

#检查日志目录
CheckDir "${logPath}"

#检查参数个数
if [ $# -ne 6 ]; then
Log "[Error] 参数输入错误, 请检查!"
Log "[Error] Eg:"
Log "[Error] sh ${shName} 本地路径 远程路径 远程IP SFTP用户 SFTP密码 GET[PUT]"
exit 1
fi

#定义主函数
execute_sftp_cmd()
{
local localPath=$1
local remotePath=$2
local serverIp=$3
local sftpUser=$4
local sftpPass=$5
local cmd=$6

log_file=${logPath}/execute_sftp_cmd.log
#如果密码中包含$符号,需要转义以下
sftpPass=`echo ${sftpPass} | sed 's/\\$/\\\\$/g'`

if [ ! -d ${localPath} ]; then
Log "[Error] 本地路径不存在, 请检查! [${localPath}]"
exit 1
fi
#切换至本地目录
cd ${localPath}
expect <<EOF > ${log_file}
set timeout 5
spawn sftp ${sftpUser}@${serverIp}:${remotePath}
expect {
"(yes/no)?"
{
send "yes\n"
expect "*password:" { send "${sftpPass}\n"}
}
"*assword:"
{
send "${sftpPass}\n"
}
}
expect "Changing to:*"
send "${cmd} *\n"
expect "sftp>"
send "exit\n"
expect eof
EOF
cat ${log_file}|tee -a ${logFile}
cat ${log_file} | grep -iE "denied|error|failed|not found" >/dev/null
if [ $? -eq 0 ];then
Log "[Error] 脚本执行失败, 请检查!"
Log "[Error] 日志文件: [${logFile}]"
Log ""
exit 1
fi
Log "[Info] 脚本执行成功."
Log ""
}

Log "[Info] 开始执行脚本:"
Log "[Info] localPath : ${localPath}"
Log "[Info] remotePath: ${remotePath}"
Log "[Info] serverIp : ${serverIp}"
Log "[Info] sftpUser : ${sftpUser}"
Log "[Info] sftpPass : ${sftpPass}"
Log "[Info] cmd : ${cmd}"
Log ""
execute_sftp_cmd "$@"

蚂蚁再小也是肉🥩!


Linux Sftp上传下载文件
http://heibanbai.com.cn/posts/7971c3cf/
作者
黑伴白
发布于
2022年10月9日
许可协议

“您的支持,我的动力!觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付