说明
通过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
shName=`basename $0`
localPath=$1 remotePath=$2 serverIp=$3 sftpUser=$4 sftpPass=$5 cmd=$6
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 "$@"
|
蚂蚁🐜再小也是肉🥩!