两台Linux服务器之间的文件传输

最近工作中有这样一个需求,需要将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 # 在执行命令时,捕获异常,调用error_exit函数
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分钟(可配置)扫描一次目录;

posted @ 2017-11-04 12:08  练子  阅读(2635)  评论(0编辑  收藏  举报