#!/bin/bash#```ops#title:bash利用ftp命令批量上传文件到远程ftp#descr:从linux服务器批量上传/var/log/polling文件夹里面文件到FTP(192.168.1.99)里面/jishu/liujian/polling目录#```updir=/var/log/polling
todir=/jishu/liujian/polling
ip=192.168.1.99
user=ljohn1
password=ljohn
sss=`find $updir -type d -printf $todir/'%P\n'|awk'{if ($0 == "")next;print "mkdir " $0}'`aaa=`find $updir -type f -printf'put %p %P \n'`ftp-nv$ip<<EOF
user $user$password
type binary
passive
prompt
$sss
cd $todir$aaa
quit
EOF# 另外一种写法# Upload file(s) to FTP server# Argument example:# 1) ./ftp_upload.sh filename# 2) ./ftp_upload.sh filename1 filename2 filename3 ...# 3) ./ftp_upload.sh "*.extension"# 4) ./ftp_upload.sh "*.extension1" "*.extension2"########### START OF CONFIG ########### Local directory (current folder)LOCALDIR=$(pwd)# File to log the outcome of backupsLOGFILE="/var/log/ftp_upload.log"# FTP server# Enter the Hostname or IP address belowFTP_HOST="192.168.1.99"# FTP username# Enter the FTP username belowFTP_USER="ljohn1"# FTP password# Enter the username's password belowFTP_PASS="ljohn"# FTP server remote folder# Enter the FTP remote folder below# For example: public_htmlFTP_DIR="/"########## END OF CONFIG ##########log(){echo"$(date"+%Y-%m-%d %H:%M:%S")""$1"echo-e"$(date"+%Y-%m-%d %H:%M:%S")""$1">>${LOGFILE}}# Check ftp commandcheck_command(){if[!"$(command-v"ftp")"];then
log "ftp command is not installed, please install it and try again"exit1fi}# Tranferring backup file to FTP serverftp_upload(){cd${LOCALDIR}||exit[-z${FTP_HOST}]&& log "Error: FTP_HOST can not be empty!"&&exit1[-z${FTP_USER}]&& log "Error: FTP_USER can not be empty!"&&exit1[-z${FTP_PASS}]&& log "Error: FTP_PASS can not be empty!"&&exit1[-z${FTP_DIR}]&& log "Error: FTP_DIR can not be empty!"&&exit1echo"$@"|grep"*"> /dev/null 2>&1if[$?-eq0];thenls$@> /dev/null 2>&1[$?-ne0]&& log "Error: [$@] file(s) not exists!"&&exit1elseforfin$@do[!-f${f}]&& log "Error: [${f}] not exists!"&&exit1donefilocalFTP_OUT_FILE=("$@")
log "Tranferring file(s) list below to FTP server:"forfilein${FTP_OUT_FILE[@]}do
log "$file"doneftp-in${FTP_HOST}2>&1>>${LOGFILE}<<EOF
user $FTP_USER$FTP_PASS
binary
lcd $LOCALDIR
cd $FTP_DIR
mput ${FTP_OUT_FILE[@]}
quit
EOF
log "Tranfer to FTP server completed"}# Main progressSTARTTIME=$(date +%s)[$#-eq0]&& log "Error: argument can not be empty!"&&exit1
check_command
ftp_upload "$@"ENDTIME=$(date +%s)DURATION=$((ENDTIME - STARTTIME))
log "All done"
log "Transfer completed in ${DURATION} seconds"