三步實現利用定時任務同步文件
一、配置免密登錄
- 數據傳輸的前提是兩個服務器之間的通信是免密通信,如果不是,按照如下方式設置,假設需要將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