本文描述了linux下使用rsync單向同步兩個(gè)機(jī)器目錄的問題。 使用rsync同步后可以保持目錄的一致性(含刪除操作)。
數(shù)據(jù)同步方式
1、從主機(jī)拉數(shù)據(jù)
備機(jī)上啟動的流程
同步命令:
rsync -avzP --delete root@{remoteHost}:{remoteDir} {localDir}參數(shù)說明:
示例:
rsync -avzP --delete root@192.168.1.100:/tmp/rtest1 /tmp/
2、向備機(jī)推數(shù)據(jù)
主機(jī)上啟動的流程
同步命令:
rsync -avzP --delete {localDir} root@{remoteHost}:{remoteDir}示例:
rsync -avzP --delete /tmp/rtest1 root@192.168.1.101:/tmp/
自動同步配置
描述同步時(shí)不輸入密碼的配置的方法。
1、使用ssh key
該方法可以直接使用rsync命令進(jìn)行同步,同步過程中無需輸入密碼。
在主機(jī)上產(chǎn)生ssh key :
ssh-keygen -t rsa
在備機(jī)上加入pubkey
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.101
或者手動添加:
在主機(jī)上執(zhí)行以下命令獲取pubkey:
cat ~/.ssh/id_rsa.pub
在備機(jī)上加入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實(shí)現(xiàn)的代碼,大家可根據(jù)情況用其它語言實(shí)現(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掉是安全的,下次啟動時(shí)還可以正常工作。
2、rsync不能指定時(shí)間段;
1)該問題可以通過kill來解決
2)或者使用pexpect的timeout參數(shù)來控制
3)可以先通過find查找過濾出文件夾的名字,然后使用rsync進(jìn)行同步 這個(gè)可以根據(jù)現(xiàn)有業(yè)務(wù)的特征進(jìn)行,比如:
find /tmp -name '*' -newermt '2016-03-08' ! -newermt '2016-03-20'
3、rsync在寫文件過程中同步(比如錄音過程中執(zhí)行rsync操作)
經(jīng)測試,rsync會同步部分文件內(nèi)容,文件寫入完成后再執(zhí)行rsync會保持文件的一致
4、當(dāng)文件數(shù)量達(dá)到百萬級以上時(shí),rsync同步時(shí)掃描改變的文件非常耗時(shí)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選