Linux之rsync同步工具介紹+inotify同步

1.rsync介紹

  Rsync是一款開源的、快速的、多功能的、可實現全量及增量的本地或遠程數據同步備份的優秀工具。Rsync軟件適用於unix/linux/windows等多種操做平臺。
  rsync,remote synchronize顧名思意就知道它是一款實現遠程同步功能的軟件,它在同步文件的同時,能夠保持原來文件的權限、時間、軟硬連接等附加信息。 rsync是用 「rsync 算法」提供了一個客戶機和遠程文件服務器的文件同步的快速方法,並且能夠經過ssh方式來傳輸文件,這樣其保密性也很是好,另外它仍是免費的軟件。rsync官方文檔(http://www.samba.org/ftp/rsync/rsync.htmlhtml

    rsync 特性(Some of the additional features of rsync are)

  • support for copying links, devices, owners, groups, and permissions(支持拷貝特殊文件如連接文件,設備等)
  • exclude and exclude-from options similar to GNU tar  (能夠有排除指定文件或目錄同步的功能,至關於打包命令tar的排除功能)
  • a CVS exclude mode for ignoring the same files that CVS would ignore(能夠作到保持原文件或目錄的權限,時間,軟硬連接,屬主、組等全部屬性均不改變-p)
  • can use any transparent remote shell, including ssh or rsh(可實現增量同步,即只同步發生變化的數據,所以數據傳輸效率很高)
  • does not require super-user privileges(可使用rcp、rsh、ssh等方式來配合傳輸文件(rsync自己不對數據加密))
  • pipelining of file transfers to minimize latency costs(能夠經過socket(進程方式)傳輸文件和數據)
  • support for anonymous or authenticated rsync daemons (ideal for mirroring)(支持匿名的或認證(無需系統用戶)的進程模式傳輸,可實現方便安全的進行數據備份及鏡像)

  來源官網linux

2.rsync的工做方式

  1)單個主句本地之間數據傳輸(此時相似於cp命令)git

  rsync本地傳送模式的語法是:rsync [option...] src...[dest]github

  rsync爲同步的命令,[option]爲同步時的參數選項,src爲源,即待拷的分區,文件或者目錄等,[dest]爲目的分區文件或者目錄等web

ll  /data                <#刪除前看一下
midir /null                <#建立一個空目錄 rsync -r --delete /null /data/
ll  /data                <#刪除完後看一下

  2)藉助rcp,ssh等通道傳輸數據(此時相似於scp命令)算法

ssh-key中的scp回顧shell

scp -P 521 -rp -- /etc/hosts king@192.168.17: /tmp   <# -P 跟端口號    用戶名@ ip  :目標文件

 rsync藉助ssh通道拉取vim

rsync -avzP -e ‘ssh -p 22’ king@192.168.17:/opt /tmp <#-e 'ssh -p 22'表示經過ssh通道傳送數據,-p22可略

 3)以守護進程(socket)的方式傳輸數據(這個是rsync自身的重要功能)windows

3.rsync命令使用,參數說明

  -v, --verbose   詳細模式輸出
  -z, --compress   對備份的文件在傳輸時進行壓縮處理
  -a, --archive    歸檔模式,表示以遞歸方式傳輸文件,並保持全部文件屬性,等於-rlptgoD
  -r, --recursive     對子目錄以遞歸模式處理
  -t, --times      保持文件時間信息
  -o, --owner    保持文件屬主信息
  -g, --group     保持文件屬組信息
  -p, --perms     保持文件權限
  -R, --relative     使用相對路徑信息
  -b, --backup      建立備份,也就是對於目的已經存在有一樣的文件名時,將老的文件從新命名爲~filename。可使用--suffix選項來指定不一樣的備份文件前綴。
  --backup-dir      將備份文件(如~filename)存放在在目錄下。
  -suffix=SUFFIX      定義備份文件前綴
  -u, --update    僅僅進行更新,也就是跳過全部已經存在於DST,而且文件時間晚於要備份的文件。(不覆蓋更新的文件)
  -l, --links       保留軟鏈結
    -L, --copy-links   想對待常規文件同樣處理軟鏈結
  --copy-unsafe-links 僅僅拷貝指向SRC路徑目錄樹之外的鏈結
  --safe-links      忽略指向SRC路徑目錄樹之外的鏈結
  -H, --hard-links     保留硬鏈結
  -q, --quiet      精簡輸出模式
  -D, --devices      保持設備文件信息
  -S, --sparse      對稀疏文件進行特殊處理以節省DST的空間
  -n, --dry-run     現實哪些文件將被傳輸
  -W, --whole-file   拷貝文件,不進行增量檢測
  -x, --one-file-system 不要跨越文件系統邊界
  -B, --block-size=SIZE 檢驗算法使用的塊尺寸,默認是700字節
  -e, --rsh=COMMAND 指定使用rsh、ssh方式進行數據同步
  --rsync-path=PATH 指定遠程服務器上的rsync命令所在路徑信息
  -C, --cvs-exclude  使用和CVS同樣的方法自動忽略文件,用來排除那些不但願傳輸的文件
  --existing       僅僅更新那些已經存在於DST的文件,而不備份那些新建立的文件
  --delete          刪除那些DST中SRC沒有的文件
  --delete-excluded    一樣刪除接收端那些被該選項指定排除的文件
  --delete-after      傳輸結束之後再刪除
  --ignore-errors    及時出現IO錯誤也進行刪除
  --max-delete=NUM  最多刪除NUM個文件
  --partial        保留那些因故沒有徹底傳輸的文件,以是加快隨後的再次傳輸
  --force             強制刪除目錄,即便不爲空
  --numeric-ids    不將數字的用戶和組ID匹配爲用戶名和組名
  --timeout=TIME    IP超時時間,單位爲秒
  -I, --ignore-times    不跳過那些有一樣的時間和長度的文件
  --size-only       當決定是否要備份文件時,僅僅察看文件大小而不考慮文件時間
  --modify-window=NUM 決定文件是否時間相同時使用的時間戳窗口,默認爲0
  -T --temp-dir=DIR 在DIR中建立臨時文件
  --compare-dest=DIR 一樣比較DIR中的文件來決定是否須要備份
  -P 等同於 --partial
  --progress         顯示備份過程
  --exclude=PATTERN     指定排除不須要傳輸的文件模式
  --include=PATTERN      指定不排除而須要傳輸的文件模式
  --exclude-from=FILE     排除FILE中指定模式的文件
  --include-from=FILE     不排除FILE指定模式匹配的文件
  --version          打印版本信息
  --address         綁定到特定的地址
  --config=FILE        指定其餘的配置文件,不使用默認的rsyncd.conf文件
  --port=PORT       指定其餘的rsync服務端口
  --blocking-io        對遠程shell使用阻塞IO
  -stats          給出某些文件的傳輸狀態
  --progress        在傳輸時現實傳輸過程
  --log-format=formAT     指定日誌文件格式
  --password-file=FILE     從FILE中獲得密碼
  --bwlimit=KBPS      限制I/O帶寬,KBytes per second
  -h, --help        顯示幫助信息
  不少對吧?簡單工做中我就只用過avz,哈哈哈安全

4.rsync服務端,客戶端安裝配置  

 1)服務端安裝配置

以守護進程(socket)的方式傳輸數據

[king@rsyncserver ~]$ rpm -qa rsync   #查看是否安裝rsync rsync-3.0.6-9.el6_4.1.x86_64 [king@rsyncserver ~]$ vim /etc/rsyncd.conf   #/etc/rsyncd.conf默認是不存在的,因此咱們要建立它並編輯它 #rsync_config_______________start ##rsyncd.conf start## uid = rsync                    #rsync使用的用戶,缺省uid爲-2,一般爲 nobody gid = rsync                    #rsync使用的組(用戶所在的組)缺省gid爲-2,一般爲nobody use chroot = no                  max connections = 200              #設置最大的鏈接數,默認爲0,就是無限制,負值爲關閉這個模塊 timeout = 60                   #默認爲0,鏈接超時, pid file = /var/run/rsyncd.pid         #rsync daemon啓動後將其進程PID寫入此文件 lock file = /var/run/rsync.lock         #鎖的機制 log file = /var/log/rsyncd.log         #日誌配置文件,報錯咱們查看他它 [king]                       #用戶模塊          path = /king/                   #用戶共享的文件 ignore errors                   #錯誤忽略(i/o) read only = false                 #指定客戶端是否能夠上傳文件,默認對全部模塊都爲true list = false                    #不顯示列表 hosts allow = 192.168.1.7/24          #指定能夠聯繫的客戶端用戶名和ip,address/mask hosts deny = 0.0.0.0/32             #默認是沒喲 auth users = rsync_backup            #auth users指定以空格或者, 分隔的用戶可使用那些模塊 secrets file = /etc/rsync.password      #secrets file 指定用戶名和密碼的文件 格式 用戶名:密碼 #rsync_config_______________end ~ [root@rsyncserver /]# chown -R rsync.rsync king/ #建立共享目錄,並讓rsync用戶能夠管理king [root@rsyncserver ~]# chmod 600 /etc/rsync.password       #用戶密碼文件只能是600 [root@rsyncserver king]# ls -lh /etc/rsync.password -rw-------. 1 root root 19 9月 21 10:15 /etc/rsync.password [root@rsyncserver ~]# cat /etc/rsync.password #查看用戶密碼文件,注意其格式 rsync_backup:king [root@rsyncserver ~]# rsync --daemon #啓動rsync服務,若是想要重啓服務的話,先用pkill rsync殺掉進程而後再執行此操做 [root@rsyncserver ~]# ps -ef|grep rsync|grep -v grep root 1670     1  0 13:56 ?        00:00:00 rsync --daemon 注意:要關閉防火牆和selinux [king@rsyncserver .ssh]$ sudo /etc/init.d/iptables stop [king@rsyncserver .ssh]$ sudo getenforce Enforcing [king@rsyncserver .ssh]$ sudo setenforce 0 [kingy@rsyncserver .ssh]$ getenforce Permissive

  2)客戶端安裝配置

[root@rsyncclient ~]# rpm -qa rsync rsync-3.0.6-9.el6_4.1.x86_64 [root@rsyncclient ~]# vim /etc/rsync.password [root@rsyncclient ~]# chmod 600 /etc/rsync.password [root@rsyncclient ~]# useradd -s /sbin/nologin rsync [root@rsyncclient ~]# cat /etc/rsync.password king

 3)同步

 Local: rsync [OPTION...] SRC... [DEST] Access via remote shell: Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST:DEST Access via rsync daemon: Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST] rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
 Push: rsync [OPTION...] SRC... [USER@]HOST::DEST rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST
pull: [root@rsyncclient ~]# rsync -avz rsync_backup@192.168.1.7::king /data --password-file=/etc/rsync.password receiving incremental file list ./ a b sent 105 bytes  received 224 bytes  658.00 bytes/sec total size is 8  speedup is 0.02 push: [root@rsyncclient ~]# rsync -avz   /data/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #注意/data後面有斜槓和沒斜槓的區別:沒有斜槓的話將目錄一塊同步,有斜槓的話只同步目錄下面的內容。

5.--exclude參數

1)只排除一個文件不一樣步

rsync -avz --exclude=1 rsync_backup@192.168.1.7::king /data/ --password-file=/etc/rsync.password

  --exclude= 文件名字  rsync_backup是你/etc/rsyncd.conf文件裏配置的auth users = rsync_backup  @ip   king  是你/etc/rsyncd.conf文件裏配置的[king],--password-file=/etc/rsync.password即爲讀取你的密碼文件,注意你的密碼文件權限必須是600,且格式必須是相似鍵值對的形式存在,(用戶:密碼)

2)排除多個文件不一樣步

方法一: rsync -avz --exclude={1,2} /data1/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #{文件名字用逗號隔開}
方法二:
 rsync -avz --exclude={1..3} /data1/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #{文件名字,這是文件名連續的文件}
方法三:
rsync -avz --exclude=1 --exclude=2 /data/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #多個--exclude=文件名字,雖然麻煩,不失爲方法。

3)無差別同步:--delete參數

  通常是有須要在倆臺服務器之間,必需要求數據同步,且實時性又不是很高的狀況下,如:倆臺負載均衡下面的web服務器之間的同步,或者高可用雙機配置之間的同步等,rsync無差別同步很危險切記。

 6.inotify介紹

Inotify 是一種強大的、細粒度的、異步的文件系統事件監控機制,linux內核從2.6.13起,加入了Inotify支持,經過Inotify能夠監控文件系統中添加、刪除,修改、移動等各類細微事件,利用這個內核接口,第三方軟件就能夠監控文件系統下文件的各類變化狀況,而inotify-tools就是這樣的一個第三方軟件。

inotify是rsync客戶端安裝和執行的

1 )查看當前系統是否支持inotify

[root@rsyncclient ~]# ll /proc/sys/fs/inotify/ 總用量 0
-rw-r--r-- 1 root root 0 9月  21 14:56 max_queued_events -rw-r--r-- 1 root root 0 9月  21 14:56 max_user_instances -rw-r--r-- 1 root root 0 9月  21 14:56 max_user_watches #顯示這三個文件則證實支持。

 /proc/sys/fs/inotify/max_queued_evnets      

表示調用inotify_init時分配給inotify instance中可排隊的event的數目的最大值,超出這個值的事件被丟棄,但會觸發IN_Q_OVERFLOW事件。

 /proc/sys/fs/inotify/max_user_instances 

表示每個real user ID可建立的inotify instatnces的數量上限。

 /proc/sys/fs/inotify/max_user_watches 

表示每一個inotify instatnces可監控的最大目錄數量。若是監控的文件數目巨大,須要根據狀況,適當增長此值的大小。

2) 下載inotify源碼包並編譯安裝

cd /home/king/tools          #安裝要規範,要有本身的文件包 wget http://github.com/downloads/rvoicilas/inotifytools/inotify-tools-3.14.tar.gz #安裝inotify軟件包
 ll inotify-tools-3.14.tar.gz    #看一下,是否下載成功,安裝包是644的權限 tar zxf inotify-tools-3.14.tar.gz  # 解壓

3)inotifywait命令經常使用參數詳解

[root@inotifyclient inotify-tools-3.14]# cd /usr/local/inotify-3.14/ [root@inotifyclient inotify-3.14]# ./bin/inotifywait --help -r|--recursive Watch directories recursively. #遞歸查詢目錄 -q|--quiet Print less (only print events). #打印監控事件的信息 -m|--monitor   Keep listening for events forever.  Without this option, inotifywait will exit after one  event is received. #始終保持事件監聽狀態 --excludei <pattern>  Like --exclude but case insensitive. #排除文件或目錄時,不區分大小寫。 --timefmt <fmt> strftime-compatible format string for use with %T in --format string. #指定時間輸出的格式 --format <fmt>  Print using a specified printf-like format string; read the man page for more details. #打印使用指定的輸出相似格式字符串 -e|--event <event1> [ -e|--event <event2> ... ] Listen for specific event(s).  If omitted, all events are  listened for. 
#經過此參數能夠指定須要監控的事件,以下所示: Events: access file or directory contents were read #文件或目錄被讀取。 modify file or directory contents were written #文件或目錄內容被修改。 attrib file or directory attributes changed #文件或目錄屬性被改變。 close file or directory closed, regardless of read
/write mode #文件或目錄封閉,不管讀/寫模式。 open file or directory opened #文件或目錄被打開。 moved_to file or directory moved to watched directory #文件或目錄被移動至另一個目錄。 move file or directory moved to or from watched directory #文件或目錄被移動另外一個目錄或從另外一個目錄移動至當前目錄。 create file or directory created within watched directory #文件或目錄被建立在當前目錄 delete file or directory deleted within watched directory #文件或目錄被刪除 unmount file system containing file or directory unmounted #文件系統被卸載

4 )編寫監控腳本並加載到後臺執行

mkdir -p /etc/servers/scripts      #咱們要建立這個存放腳本的目錄,爲了規範 cd /etc/servers/scripts           vim inotify.sh               #編輯這個腳本

腳本內容以下

#!/bin/shpath=/usr/local/inotify/bin/inotifywait
$path -mrq --format '%w%f' -e create,close_write,delete /backup|\
while read line
do
  [! -e "$line"]&& continue
  
rsync -avz --delete $line rsync_backup@192.168.1.7::king /data/ --password-file=/etc/rsync.password
done
sh inotify.sh &  #將腳本加入後臺執行

 說明:\是換行的意思,continue是跳過下面的命令,相似於Java中的\t \n,continue,continue 跳出當前循環,不執行continue後續循環體內的代碼,從新執行下次循環體,break 跳出循環體,直接結束循環,執行循環後的代碼 好比:

pulic void TestBreak(){   for(int i=0; i < 10; i++){     if (i == 5) {       break;     } else {       System.out.print(i);     }   }   System.out.print("end"); } 輸出結果:01234end pulic void TestContinue(){   for(int i=0; i < 10; i++){     if (i == 5) {       continue ;     } else {       System.out.print(i);     }   }   System.out.print("end"); } 輸出結果:012346789end

簡單說說吧,雖然我寫代碼不少bug,可是很開心呀

相關文章
相關標籤/搜索