需求是這樣的:目錄裡隨時可能有新檔案產生,要把它們自動送到前置機。做法是用無窮迴圈每分鐘掃一次,只挑「修改時間超過 1 分鐘但未超過 2 分鐘」的檔案,避免同一個檔被重複上傳。
#!/bin/ksh
########################################################
#Date: 2012-12-19
#name: swiftftp.sh
#description: 無限循環,每 1 分鐘執行一次,查找當前目錄中
# 修改時間超過 1 分鐘但未超過 2 分鐘的檔案,ftp 到前置機
########################################################
datestr=`date "+%Y%m%d"`
_logname=dynamicftp${datestr}.log
chmod +x *
if [[ ! -f ${_logname} ]];then
touch ${_logname};
fi
檔案的修改時間是 yyyymmddhhmm.ss 格式,而 touch -t 正好吃這個格式,所以只要算出「N 分鐘前」的時間戳,就能造出兩個參照檔:
# 該函數印出參數 1 的時間戳
cal_timestamp() {
perl -e '
use Time::Local;
# 參數表示要求返回 minu_num 個分鐘之前的時間戳 yyyymmddhhmm.ss
$minu_num="$ARGV[0]";
localtime(time);
$time1= time -60*$minu_num;
($sec,$min,$hr,$mday,$mon,$yr,$wday,$yday,$isdst)=localtime($time1);
$yr=$yr+1900;
$mon=$mon+1;
$beforetime=sprintf("%d%02d%02d%02d%02d.%02d",$yr,$mon,$mday,$hr,$min,$sec);
print "$beforetime"
' "$1"
}
# 最外層循環
while [[ 1 -eq 1 ]] ; do
oneminubef=$( cal_timestamp "1")
echo "1 minutes before:$oneminubef" >> ${_logname}
twominubef=$( cal_timestamp "2")
echo "2 minutes before:$twominubef" >> ${_logname}
# 建立兩個參照檔
touch -t $oneminubef oneminubef.tmp
touch -t $twominubef twominubef.tmp
# 找出比 2 分鐘前新、但比 1 分鐘前舊的檔案
# find 用法: find -newer file1 ! -newer file2
touch tempfile01
chmod 777 tempfile01
find . -newer twominubef.tmp ! -newer oneminubef.tmp | grep -v '^./oneminubef.tmp' | grep -v "^./${_logname}" | grep -v "{0}" > tempfile01
# 讀出清單並拼接檔名
a=0
filenames=
while read line
do
line=`echo $line | sed -e 's/^ *//' -e 's/ *$//'` # 去除空白
length=`echo ${line} | awk '{print length($1);}'` # 計算字元數
if [[ ${length} -gt 0 ]]; then # 防止空行
newline=${line#*/} # 去除檔名前面的 ./
filenames=$filenames" "$newline
a=`expr $a + 1`
fi
done < tempfile01
rm -rf tempfile01 oneminubef.tmp twominubef.tmp
echo "files :$filenames" >> ${_logname}
_username=test
_passwd=test
if [[ $a -gt 0 ]]; then
ftp -in 192.168.93.77 << !
user ${_username} ${_passwd}
bi
mput $filenames
bye
! fi
if [[ $? -eq 0 && a -gt 0 ]]; then
echo `date`" successfully put $a files on server" >> ${_logname}
elif [[ a -gt 0 ]]; then
echo `date`" put files error!" >> ${_logname}
else
echo `date`" no files need to be put!" >> ${_logname}
fi
sleep 60
done
幾處值得注意的設計:ftp 的 -i 關閉互動提示、-n 不自動登入,配合 here-document 一次把帳密、二進位模式與 mput 餵進去;bi 是 binary 的縮寫,傳二進位檔一定要加,否則圖片壓縮檔會損壞;排除清單裡要記得把日誌檔與參照檔濾掉,不然會自己傳自己。
實務上的建議:帳密直接寫在腳本裡風險偏高,可改用 ~/.netrc 並設為 600;另外與其依賴「1 到 2 分鐘」這種時間窗,不如改用 inotify 監聽目錄事件,會更即時也更可靠。