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


1.rsync介紹

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

    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)(支持匿名的或認證(無需系統用戶)的進程模式傳輸,可實現方便安全的進行數據備份及鏡像)

  來源官網

2.rsync的工作方式

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

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

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

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

  2)借助rcp,ssh等通道傳輸數據(此時類似於scp命令)

ssh-key中的scp回顧

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

 rsync借助ssh通道拉取

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

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

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,但是很開心呀


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM