linux环境两台服务器间利用定时任务同步文件脚本

三步实现利用定时任务同步文件

一、配置免密登录

  1. 数据传输的前提是两个服务器之间的通信是免密通信,如果不是,按照如下方式设置,假设需要将serverA文件无密传输给serverB,则配置规则为:

           a)  进入serverA,在命令行中输入ssh-keygen,然后连续回车即可,出现如下界面就ok

           b) 复制公钥到目标服务器serverB,在serverA中执行如下语句:

                ssh-copy-id -i /root/.ssh/id_rsa.pub root@serverB的IP      #复制密钥

               回车,输入目标服务器serverB的密码即可

           c)      完成上述操作即可实现密码登录,可通过ssh serverB的IP 验证是否成功

 

二、编写shell脚本

       同步原理:读取时间戳文件中的时间,与目标被同步文件的修改时间做比对,如果文件时间较新,则同步。否则,认为该文件已经同步,不再需要同步

       在/tesh/目录中创建task4syncFile.sh(内容如下),lastSyncTime.txt(默认填0)和logs日志目录

#!/bin/bash
#脚本名称:在两台linux主机间同步指定目录的文件
#配置定时任务方法
#crontab -e
#输入命令并保存退出  * * * * * /tesh/task4syncFile.sh >> /tesh/logs/syncFile_$(date "+\%Y-\%m-\%d").log 2>&1
function syncFile(){
    if [ ! -d "$src_file_dir" ];then
       echo "===>target dir [${src_file_dir}] is not existed,exit."
       return
    fi
    formatedTimeStr=$(date -d @$lastSyncTimeStamp "+%Y-%m-%d %T")
    echo "=========>begin sync file,the last sync time is $formatedTimeStr <========="
    syncd='false'
    #根据文件修改时间升序排列
    for file in `ls -rt $1`
    do
      dir_or_file=$1"/"$file
      #echo "当前文件:$dir_or_file"
      if test -f $dir_or_file
      then
         filetimestamp=`stat -c %Y $dir_or_file`        
         timecha=$[$filetimestamp - $lastSyncTimeStamp]
         #echo "time dif is "$timecha
         if [ $timecha -gt 0 ];then
           syncd='true'
           
           echo "===>trans file $dir_or_file to $target_host_ip:$target_file_dir ..."
           scp -r $dir_or_file $target_host_userName@$target_host_ip:$target_file_dir/$file
           if [ "$?" -eq "0" ];
           then
             echo "file[$dir_or_file] trans successful!!!"
           else 
             echo "$file[$dir_or_file] trans fail!!!"
              scp -r $dir_or_file $target_host_userName@$target_host_ip:$target_file_dir/$file
              if [ "$?" -ne "0" ];then
                echo "$dir_or_file传输失败,请手动上传"
                      fi    
               fi             
         fi
      fi
      if test -d $dir_or_file
      then
        syncFile $dir_or_file
      fi
    done
    if [ $syncd = 'true' ];then
      echo "===>sync file task finished,write the last file timestamp $filetimestamp to $timeFile."
      echo $filetimestamp > $timeFile
    else
      echo "===>no file should be syncd,exit."
    fi
    echo "======================================================="
    
}
#记录最后一个被同步文件的时间戳,单位为秒,手动配置
timeFile=/cloud/tesh/lastSyncTime.txt
lastSyncTimeStamp=$(cat $timeFile)
#源文件根目录,手动配置
src_file_dir=/cloud/tesh/file
#目标主机用户名,手动配置
target_host_userName=root
#目标主机IP地址,手动配置
target_host_ip=10.80.4.152
#目标主机文件根目录,手动配置
target_file_dir=/cloud/tesh/dir
#调用同步文件函数
syncFile $src_file_dir

三、在linux中创建定时任务    

执行命令 crontab -e
输入如下文本保存退出即可
* * * * * /tesh/task4syncFile.sh >> /tesh/logs/syncFile_$(date "+\%Y-\%m-\%d").log 2>&1
 
posted @ 2022-03-19 15:18  Franson  阅读(1758)  评论(0编辑  收藏  举报