本文描述了linux下使用rsync單向同步兩個機器目錄的問題。 使用rsync同步后可以保持目錄的一致性(含刪除操作)。
數(shù)據(jù)同步方式
1、從主機拉數(shù)據(jù)
備機上啟動的流程
同步命令:
rsync -avzP --delete root@{remoteHost}:{remoteDir} {localDir}參數(shù)說明:
-a 參數(shù),相當(dāng)于-rlptgoD(-r 是遞歸 -l 是鏈接文件,意思是拷貝鏈接文件;-p 表示保持文件原有權(quán)限;-t 保持文件原有時間;-g 保持文件原有用戶組;-o 保持文件原有屬主;-D 相當(dāng)于塊設(shè)備文件); -z 傳輸時壓縮; -P 傳輸進度; -v 傳輸時的進度等信息;示例:
rsync -avzP --delete root@192.168.1.100:/tmp/rtest1 /tmp/
2、向備機推數(shù)據(jù)
主機上啟動的流程
同步命令:
rsync -avzP --delete {localDir} root@{remoteHost}:{remoteDir}示例:
rsync -avzP --delete /tmp/rtest1 root@192.168.1.101:/tmp/
自動同步配置
描述同步時不輸入密碼的配置的方法。
1、使用ssh key
該方法可以直接使用rsync命令進行同步,同步過程中無需輸入密碼。
在主機上產(chǎn)生ssh key :
ssh-keygen -t rsa
在備機上加入pubkey
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.101
或者手動添加:
在主機上執(zhí)行以下命令獲取pubkey:
cat ~/.ssh/id_rsa.pub
在備機上加入key內(nèi)容:
vi ~/.ssh/authorized_keys
使用pexpect自動輸入密碼
示例代碼如下:
#!/usr/bin/env python# -*- coding: utf-8 -*-import pexpectimport timeimport tracebackdef doRsync(user,passwd,ip,srcDir,dstDir,timeout=3600): cmd = "rsync -azPq --delete {srcDir} {rUser}@{rHost}:{dstDir}".format( rUser = user,rHost=ip,srcDir=srcDir,dstDir=dstDir ) try: ssh = pexpect.spawn(cmd,timeout=timeout) print cmd i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) if i == 0 : ssh.sendline(passwd) elif i == 1: ssh.sendline('yes') ssh.expect('password: ') ssh.sendline(passwd) ssh.read() ssh.close() except : #print traceback.format_exc() passif __name__ == '__main__': doRsync("root","123456","192.168.1.101","/tmp/rtest1","/tmp")上面是使用python實現(xiàn)的代碼,大家可根據(jù)情況用其它語言實現(xiàn)該功能。
其它
1、rsync在執(zhí)行過程中被kill掉會怎么樣;
It is safe to kill an rsync process and run the whole thing again; it will continue where it left off. It may be a little inefficient, particularly if you haven't passed --partial (included in -P), because rsync will check all files again and process the file it was interrupted on from scratch.
rsync被kill掉是安全的,下次啟動時還可以正常工作。
2、rsync不能指定時間段;
1)該問題可以通過kill來解決
2)或者使用pexpect的timeout參數(shù)來控制
3)可以先通過find查找過濾出文件夾的名字,然后使用rsync進行同步 這個可以根據(jù)現(xiàn)有業(yè)務(wù)的特征進行,比如:
新聞熱點
疑難解答