1. 程式人生 > >兩臺Linux服務器之間的文件傳輸

兩臺Linux服務器之間的文件傳輸

date shell腳本 color path 日期格 targe 目錄 get remote

最近工作中有這樣一個需求,需要將A服務器上的文件傳到B服務器。

本來想用Java開發,但一想Java開發周期長,應對這樣一個小需求沒必要用Java,最後選擇了Shell腳本,相關代碼如下:

 1 #!/bin/bash
 2 
 3 function error_exit {
 4   echo "$1" 1>&2
 5   exit 1
 6 }
 7 
 8 # 本地目錄(可修改項)
 9 sourcePath=/opt/file
11 # 遠程服務器IP,端口,目錄(可修改項)
12 targetIp=192.168.1.100
13 targetPort=22
14 targetPath=/opt/file
16
# 間隔多久掃描一次目錄(可修改項) 17 sleepTime=300 18 19 20 while true 21 do 22 nowTime=`date +%Y-%m-%d %H:%M:%S` 23 echo "$nowTime - start scan dir files..." 24 curday=`date +%Y%m%d` 25 # 創建目錄 26 targetDatePath="$targetPath/$curday" 27 ssh -p $targetPort $targetIp "[ -d $targetDatePath ]" >/dev/null 2
>&1 28 if [ $? != 0 ] 29 then 30 echo "$nowTime - auto create remote dir $targetDatePath ..." 31 ssh -p $targetPort $targetIp "mkdir $targetDatePath" || error_exit "$nowTime - Line number:$LINENO ,create remote dir failed, exit..." 32 fi 33 34 for file in $(find $sourcePath/$curday -name "
*.xml") 35 do 36 scp -P $targetPort $file $targetIp:$targetDatePath || error_exit "$nowTime - Line number:$LINENO ,scp file failed, exit..." 37 38 rm -rf $file 39 done 40 echo "$nowTime - end scan dir files..." 41 sleep $sleepTime 42 done

指定本地目錄,本地目錄下是以日期格式為目錄名的一系列子目錄,掃描出日期目錄下的所有xml文件;

傳輸到遠程服務器,遠程目錄下如果沒有對應的日期目錄則創建,有就不創建,並且5分鐘(可配置)掃描一次目錄;

兩臺Linux服務器之間的文件傳輸