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

本文介绍了一种使用Shell脚本实现从本地服务器定期扫描特定目录下的XML文件,并将其传输到远程服务器的方法。该脚本会检查远程服务器上是否已存在对应日期的目录,若不存在则自动创建。

最近工作中有这样一个需求,需要将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分钟(可配置)扫描一次目录;

转载于:https://www.cnblogs.com/lianliang/p/7782984.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值