linux下使用rsync同步目錄_Linux

來源:互聯網
上載者:User

本文描述了linux下使用rsync單向同步兩個機器目錄的問題。 使用rsync同步後可以保持目錄的一致性(含刪除操作)。

資料同步方式

1、從主機拉資料

備機上啟動的流程

同步命令:

rsync -avzP --delete root@{remoteHost}:{remoteDir} {localDir}

參數說明:

  • -a 參數,相當於-rlptgoD(-r 是遞迴 -l 是連結檔案,意思是拷貝連結檔案;-p 表示保持檔案原有許可權;-t 保持檔案原有時間;-g 保持檔案原有使用者組;-o 保持檔案原有屬主;-D 相當於塊裝置檔案);
  • -z 傳輸時壓縮;
  • -P 傳輸進度;
  • -v 傳輸時的進度等資訊;

樣本:

rsync -avzP --delete root@192.168.1.100:/tmp/rtest1 /tmp/

2、向備機推資料

主機上啟動的流程

同步命令:

rsync -avzP --delete {localDir} root@{remoteHost}:{remoteDir}

樣本:

rsync -avzP --delete /tmp/rtest1 root@192.168.1.101:/tmp/

自動同步配置

描述同步時不輸入密碼的配置的方法。

1、使用ssh key

該方法可以直接使用rsync命令進行同步,同步過程中無需輸入密碼。

在主機上產生ssh key :

ssh-keygen -t rsa

在備機上加入pubkey

ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.101

或者手動添加:

在主機上執行以下命令擷取pubkey:

cat ~/.ssh/id_rsa.pub

在備機上加入key內容:

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實現的代碼,大家可根據情況用其它語言實現該功能。

其它

1、rsync在執行過程中被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參數來控制

3)可以先通過find尋找過濾出檔案夾的名字,然後使用rsync進行同步 這個可以根據現有業務的特徵進行,比如:

find /tmp -name '*' -newermt '2016-03-08' ! -newermt '2016-03-20'

3、rsync在寫檔案過程中同步(比如錄音過程中執行rsync操作)

經測試,rsync會同步部分檔案內容,檔案寫入完成後再執行rsync會保持檔案的一致

4、當檔案數量達到百萬級以上時,rsync同步時掃描改變的檔案非常耗時

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.