Rsync+inotify實現文件實時同步
數據備份、文件備份是運維、DBA等崗位最熟悉不過的話題,這裏不介紹數據庫的備份,簡單介紹一下文件同步工具,這樣的工具有很多,Windows環境下有Goodsync、FreeFileSync等,Linux下rsync、unison等,常用的實時同步,是幾種工具的組合,經過組合的工具達到文件實時同步的效果。
一、常用實時同步方案
1、NFS網絡文件系統
該方案是分布式架構中,解決不同節點對同一資源訪問的問題,搭建NFS服務器,將其掛載在不同的節點,每個節點將公用的數據存儲在NFS服務器上,實現文件的同步。
2、rsync+inotify
該方案是實用量最大,資料最豐富的文件同步方案,rsync主要有基於系統用戶和虛擬用戶的兩種方式,基於系統用戶的方式和scp命令功能特性差不多,簡單實用,可操作性強。inotify主要用來監控文件的變換,通過兩者組合,編寫一些簡單的腳本,就可以實現文件和目錄的實時同步。也是本文重點介紹的內容。
3、rsync+sersync
sersync是基於inotify開發的工具,類似於inotify-tools工具,但是sersync可以記錄下被監聽目錄中發生變化的(包括增加、刪除、修改)具體某一個文件或者某一個目錄的名字,然後使用rsync同步的時候,只同步發生變化的文件或者目錄。
rsync+sersync組合的特點
a、sersync可以記錄被監聽目錄中發生變化的(增,刪,改)具體某個文件或目錄的名字;
b、rsync在同步時,只同步發生變化的文件或目錄(每次發生變化的數據相對整個同步目錄數據來說很小,rsync在遍歷查找對比文件時,速度很快),因此效率很高。
rsync+sersync和rsync+inotify的選型
1、同步的目錄數據量不大時,建議使用rsync+inotify
2、同步的目錄數據量很大時(幾百G甚至1T以上)文件很多時,建議使用rsync+sersync
4、unison+inotify
Unison是一款跨平臺的文件同步工具,不僅支持本地對本地同步,也支持通過SSH、RSH和Socket等網絡協議進行同步。更棒的是,Unison支持雙向同步操作,你既可以從A同步到B,也可以從B同步到A,這些都不需要額外的設定。
官方文檔:
http://www.seas.upenn.edu/~bcpierce/unison//download/releases/stable/unison-2.48.4-manual.html
二、基本環境
操作系統:CentOS 6.9
rsync版本: rsync version 3.0.6 官網:https://rsync.samba.org/
操作系統內核:2.6.32-696.6.3.el6.x86_64
inotify版本:inotify-tools-3.14 下載地址如下:
http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
三、rsync的介紹
1、rsyn的特性
可以鏡像保存整個目錄樹和文件系統。
可以很容易做到保持原來文件的權限、時間、軟硬鏈接等等。
無須特殊權限即可安裝。
快速:第一次同步時 rsync 會復制全部內容,但在下一次只傳輸修改過的文件。
壓縮傳輸:rsync 在傳輸數據的過程中可以實行壓縮及解壓縮操作,因此可以使用更少的帶寬。
安全:可以使用scp、ssh等方式來傳輸文件,當然也可以通過直接的socket連接。
支持匿名傳輸,以方便進行網站鏡象。
選擇性保持:符號連接,硬鏈接,文件屬性,權限,時間等
2、rsync與scp的區別
scp無法滿足大量數據備份,類似windows的復制
rsync支持變復制 ,邊統計,邊比較
3、rsync 數據同步方式
推push:一臺主機負責吧數據傳送給其他主機,服務器開銷很大,比較適合後端服務器少的情況
拉pull: 所有主機定時去找一主機拉數據,可能就會導致數據緩慢
推:目的主機配置為rsync服務器,源主機周期性的使用rsync命令把要同步的目錄推過去
拉:源主機配置為rsync服務器,目的主機周期性的使用rsync命令把要同步的目錄拉過來
兩種方案,rsync都有對應的命令來實現
4、Xinetd管理Rsync工作原理
5、rsync 命令
rsync命令和scp命令很相似 常用參數: -a, --archive archive mode 權限保存模式,相當於 -rlptgoD 參數,存檔,遞歸,保持屬性等 -r, --recursive 復制所有下面的資料,遞歸處理 -p, --perms 保留檔案權限 ,文件原有屬性 -t, --times 保留時間點,文件原有時間 -g, --group 保留原有屬組 -o, --owner 保留檔案所有者(root only) -D, --devices 保留device資訊(root only) -l, --links 復制所有的連接 ,拷貝連接文件 -z, --compress 壓縮模式, 當資料在傳送到目的端進行檔案壓縮. –azP -H, --hard-links 保留硬鏈接文件 -A, --acls 保留ACL屬性文件,需要配合--perms -P,-P參數和 --partial --progress 相同.只是為了把參數簡單化,表示傳進度 --version, 輸出rsync版本 -v , --verbose 復雜的輸出信息 -u, --update 僅僅進行更新,也就是跳過已經存在的目標位置,並且文件時間要晚於要備份的文件,不覆蓋新的文件 --port=PORT, 定義rsyncd(daemon)要運行的port(預設為tcp 873) --delete, 刪除那些目標位置有的文件而備份源沒有的文件 --password-file=FILE ,從 FILE 中得到密碼 --bwlimit=KBPS, 限制 I/O 帶寬 --filter “-filename”,需要過濾的文件 --exclude=filname,需要過濾的文件 --progress,顯示備份過程 幫助文檔 [[email protected] install]# rsync --help rsync version 3.0.6 protocol version 30 Copyright (C) 1996-2009 by Andrew Tridgell, Wayne Davison, and others. Web site: http://rsync.samba.org/ Capabilities: 64-bit files, 64-bit inums, 64-bit timestamps, 64-bit long ints, socketpairs, hardlinks, symlinks, IPv6, batchfiles, inplace, append, ACLs, xattrs, iconv, symtimes rsync comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the GNU General Public Licence for details. rsync is a file transfer program capable of efficient remote update via a fast differencing algorithm. Usage: rsync [OPTION]... SRC [SRC]... DEST or rsync [OPTION]... SRC [SRC]... [[email protected]]HOST:DEST or rsync [OPTION]... SRC [SRC]... [[email protected]]HOST::DEST or rsync [OPTION]... SRC [SRC]... rsync://[[email protected]]HOST[:PORT]/DEST or rsync [OPTION]... [[email protected]]HOST:SRC [DEST] or rsync [OPTION]... [[email protected]]HOST::SRC [DEST] or rsync [OPTION]... rsync://[[email protected]]HOST[:PORT]/SRC [DEST] The ‘:‘ usages connect via remote shell, while ‘::‘ & ‘rsync://‘ usages connect to an rsync daemon, and require SRC or DEST to start with a module name. Options -v, --verbose increase verbosity -q, --quiet suppress non-error messages --no-motd suppress daemon-mode MOTD (see manpage caveat) -c, --checksum skip based on checksum, not mod-time & size -a, --archive archive mode; equals -rlptgoD (no -H,-A,-X) --no-OPTION turn off an implied OPTION (e.g. --no-D) -r, --recursive recurse into directories -R, --relative use relative path names --no-implied-dirs don‘t send implied dirs with --relative -b, --backup make backups (see --suffix & --backup-dir) --backup-dir=DIR make backups into hierarchy based in DIR --suffix=SUFFIX set backup suffix (default ~ w/o --backup-dir) -u, --update skip files that are newer on the receiver --inplace update destination files in-place (SEE MAN PAGE) --append append data onto shorter files --append-verify like --append, but with old data in file checksum -d, --dirs transfer directories without recursing -l, --links copy symlinks as symlinks -L, --copy-links transform symlink into referent file/dir --copy-unsafe-links only "unsafe" symlinks are transformed --safe-links ignore symlinks that point outside the source tree -k, --copy-dirlinks transform symlink to a dir into referent dir -K, --keep-dirlinks treat symlinked dir on receiver as dir -H, --hard-links preserve hard links -p, --perms preserve permissions -E, --executability preserve the file‘s executability --chmod=CHMOD affect file and/or directory permissions -A, --acls preserve ACLs (implies --perms) -X, --xattrs preserve extended attributes -o, --owner preserve owner (super-user only) -g, --group preserve group --devices preserve device files (super-user only) --copy-devices copy device contents as regular file --specials preserve special files -D same as --devices --specials -t, --times preserve modification times -O, --omit-dir-times omit directories from --times --super receiver attempts super-user activities --fake-super store/recover privileged attrs using xattrs -S, --sparse handle sparse files efficiently -n, --dry-run perform a trial run with no changes made -W, --whole-file copy files whole (without delta-xfer algorithm) -x, --one-file-system don‘t cross filesystem boundaries -B, --block-size=SIZE force a fixed checksum block-size -e, --rsh=COMMAND specify the remote shell to use --rsync-path=PROGRAM specify the rsync to run on the remote machine --existing skip creating new files on receiver --ignore-existing skip updating files that already exist on receiver --remove-source-files sender removes synchronized files (non-dirs) --del an alias for --delete-during --delete delete extraneous files from destination dirs --delete-before receiver deletes before transfer, not during --delete-during receiver deletes during transfer (default) --delete-delay find deletions during, delete after --delete-after receiver deletes after transfer, not during --delete-excluded also delete excluded files from destination dirs --ignore-errors delete even if there are I/O errors --force force deletion of directories even if not empty --max-delete=NUM don‘t delete more than NUM files --max-size=SIZE don‘t transfer any file larger than SIZE --min-size=SIZE don‘t transfer any file smaller than SIZE --partial keep partially transferred files --partial-dir=DIR put a partially transferred file into DIR --delay-updates put all updated files into place at transfer‘s end -m, --prune-empty-dirs prune empty directory chains from the file-list --numeric-ids don‘t map uid/gid values by user/group name --timeout=SECONDS set I/O timeout in seconds --contimeout=SECONDS set daemon connection timeout in seconds -I, --ignore-times don‘t skip files that match in size and mod-time --size-only skip files that match in size --modify-window=NUM compare mod-times with reduced accuracy -T, --temp-dir=DIR create temporary files in directory DIR -y, --fuzzy find similar file for basis if no dest file --compare-dest=DIR also compare destination files relative to DIR --copy-dest=DIR ... and include copies of unchanged files --link-dest=DIR hardlink to files in DIR when unchanged -z, --compress compress file data during the transfer --compress-level=NUM explicitly set compression level --skip-compress=LIST skip compressing files with a suffix in LIST -C, --cvs-exclude auto-ignore files the same way CVS does -f, --filter=RULE add a file-filtering RULE -F same as --filter=‘dir-merge /.rsync-filter‘ repeated: --filter=‘- .rsync-filter‘ --exclude=PATTERN exclude files matching PATTERN --exclude-from=FILE read exclude patterns from FILE --include=PATTERN don‘t exclude files matching PATTERN --include-from=FILE read include patterns from FILE --files-from=FILE read list of source-file names from FILE -0, --from0 all *-from/filter files are delimited by 0s -s, --protect-args no space-splitting; only wildcard special-chars --address=ADDRESS bind address for outgoing socket to daemon --port=PORT specify double-colon alternate port number --sockopts=OPTIONS specify custom TCP options --blocking-io use blocking I/O for the remote shell --stats give some file-transfer stats -8, --8-bit-output leave high-bit chars unescaped in output -h, --human-readable output numbers in a human-readable format --progress show progress during transfer -P same as --partial --progress -i, --itemize-changes output a change-summary for all updates --out-format=FORMAT output updates using the specified FORMAT --log-file=FILE log what we‘re doing to the specified FILE --log-file-format=FMT log updates using the specified FMT --password-file=FILE read daemon-access password from FILE --list-only list the files instead of copying them --bwlimit=KBPS limit I/O bandwidth; KBytes per second --write-batch=FILE write a batched update to FILE --only-write-batch=FILE like --write-batch but w/o updating destination --read-batch=FILE read a batched update from FILE --protocol=NUM force an older protocol version to be used --iconv=CONVERT_SPEC request charset conversion of filenames -4, --ipv4 prefer IPv4 -6, --ipv6 prefer IPv6 --version print version number (-h) --help show this help (-h works with no other options) Use "rsync --daemon --help" to see the daemon-mode command-line options. Please see the rsync(1) and rsyncd.conf(5) man pages for full documentation. See http://rsync.samba.org/ for updates, bug reports, and answers
四、服務安裝與配置
1、安裝rsync
yum install -y rsync
2、基於系統用戶的備份
基於系統用戶的備份,不需要配置rsyncd服務,這時的rsync和scp非常的類似,測試規劃如下:
主機序號 | 主機IP | 備份目錄 | 安裝軟件 | 同步方式 |
1 | 192.168.223.128(數據源服務器) | /data/ | rsync | 主動方式 |
2 | 192.168.223.129(備份存儲服務器) | /databack/rsyncback | 一 | 一 |
測試:
主機:192.168.223.128 推送模式 [[email protected] ~]# cd /data [[email protected] data]# l -bash: l: command not found [[email protected] data]# ls winner.txt [[email protected] data]# ls winner.txt [[email protected] data]# rsy rsync rsyslogd [[email protected] data]# rsync -azP /data/ [email protected]:/databack/rsyncback sending incremental file list ./ .pwd.lock 0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=1/3) winner.txt 4588 100% 0.00kB/s 0:00:00 (xfer#2, to-check=0/3) sent 659 bytes received 53 bytes 284.80 bytes/sec total size is 4588 speedup is 6.44 [[email protected] data]# 主機:192.168.223.129 主機測試 [[email protected] ~]# cd /databack/rsyncback/ [[email protected] rsyncback]# ls winner.txt [[email protected] rsyncback]# 主動獲取模式測試: 在192.168.223.128 主機上創建新文件 [[email protected] data]# touch {1,3,5,7,9,10}.txt [[email protected] data]# ls 10.txt 1.txt 3.txt 5.txt 7.txt 9.txt winner.txt [[email protected] data]# 主機:192.168.223.129 獲取數據 [[email protected] rsyncback]# rsync -azP [email protected]:/data/ ./ receiving incremental file list ./ 1.txt 0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=6/9) 10.txt 0 100% 0.00kB/s 0:00:00 (xfer#2, to-check=5/9) 3.txt 0 100% 0.00kB/s 0:00:00 (xfer#3, to-check=4/9) 5.txt 0 100% 0.00kB/s 0:00:00 (xfer#4, to-check=3/9) 7.txt 0 100% 0.00kB/s 0:00:00 (xfer#5, to-check=2/9) 9.txt 0 100% 0.00kB/s 0:00:00 (xfer#6, to-check=1/9) sent 128 bytes received 368 bytes 330.67 bytes/sec total size is 4588 speedup is 9.25
從命令的執行過程中可以看出這個命令和scp非常相似,在拷貝過程中沒有輸入密碼是因為兩個主機之間做了免密碼登錄,而數據傳輸過程中也是使用了SSH傳輸協議。關於SSH免密碼登錄請自行搜索資料。
2.1 基於系統用戶的備份腳本
#!/bin/bash rsync -az --delete [email protected]:/data/ /databack/rsyncback/ tar czvf rsync-`date +%Y-%m-%d`.tar.gz /databack/rsyncback/* 執行情況: [[email protected] server]# sh -x rsync.sh + rsync -az --delete [email protected]:/data/ /databack/rsyncback/ ++ date +%Y-%m-%d + tar czvf rsync-2017-09-16.tar.gz /databack/rsyncback/10.txt /databack/rsyncback/1.txt /databack/rsyncback/3.txt /databack/rsyncback/5.txt /databack/rsyncback/7.txt /databack/rsyncback/9.txt /databack/rsyncback/winner.txt tar: 從成員名中刪除開頭的“/” /databack/rsyncback/10.txt /databack/rsyncback/1.txt /databack/rsyncback/3.txt /databack/rsyncback/5.txt /databack/rsyncback/7.txt /databack/rsyncback/9.txt /databack/rsyncback/winner.txt [[email protected] server]# [[email protected] server]# tar xzvf rsync-2017-09-16.tar.gz databack/rsyncback/10.txt databack/rsyncback/1.txt databack/rsyncback/3.txt databack/rsyncback/5.txt databack/rsyncback/7.txt databack/rsyncback/9.txt databack/rsyncback/winner.txt [[email protected] server]# ls databack rsync-2017-09-16.tar.gz rsync.sh xtrabackupmysql.sh [[email protected] server]# cd databack/rsyncback/ [[email protected] rsyncback]# ls 10.txt 1.txt 3.txt 5.txt 7.txt 9.txt winner.txt [[email protected] rsyncback]#
2.2 基於系統用戶的實時備份
在實時備份中,我們會選用inotif做文件的監控,安裝方式為源碼包,需要gcc等安裝環境,文件下載等根據上面的地址下載就可以,可以使用wget加地址下載,下面對下載和安裝做相關的演示。
數據實時同步規劃(rsync+系統用戶) | ||||
主機序號 | 主機IP | 備份目錄 | 安裝軟件 | 同步方式 |
1 | 192.168.223.128(數據源服務器) | /data/ | rsync+inotify | 主動方式 |
2 | 192.168.223.129(備份存儲服務器) | /databack/rsyncback | 一 | 一 |
[[email protected] install]# wget http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz --2017-09-16 23:35:15-- http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz 正在解析主機 github.com... 192.30.255.112, 192.30.255.113 正在連接 github.com|192.30.255.112|:80... 已連接。 已發出 HTTP 請求,正在等待回應... 302 Found 位置:http://101.96.10.63/github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz [跟隨至新的 URL] --2017-09-16 23:35:15-- http://101.96.10.63/github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz 正在連接 101.96.10.63:80... 已連接。 已發出 HTTP 請求,正在等待回應... 301 Moved Permanently 位置:https://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz [跟隨至新的 URL] --2017-09-16 23:35:16-- https://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz 正在連接 github.com|192.30.255.112|:443... 已連接。 已發出 HTTP 請求,正在等待回應... 302 Found 位置:https://cloud.github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz [跟隨至新的 URL] --2017-09-16 23:35:18-- https://cloud.github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz 正在解析主機 cloud.github.com... 54.192.75.93, 54.192.75.223, 54.192.75.185, ... 正在連接 cloud.github.com|54.192.75.93|:443... 已連接。 已發出 HTTP 請求,正在等待回應... 200 OK 長度:358772 (350K) [null] 正在保存至: “inotify-tools-3.14.tar.gz” 31% [===============> ] 113,669 36.5K/s eta(英國中部時36% [=================> ] 130,053 35.6K/s eta(英國中部時45% [======================> ] 162,821 38.5K/s eta(英國中部時54% [===========================> ] 195,589 40.9K/s eta(英國中部時58% [=============================> ] 211,517 41.3K/s eta(英國中部時63% [================================> ] 227,901 33.1K/s eta(英國中部時68% [==================================> ] 244,285 28.3K/s eta(英國中部時72% [====================================> ] 260,669 28.1K/s eta(英國中部時77% [=======================================> ] 277,509 25.6K/s eta(英國中部時81% [=========================================> ] 293,893 20.5K/s eta(英國中部時86% [===========================================> ] 310,277 20.7K/s eta(英國中部時91% [==============================================> ] 326,661 18.2K/s eta(英國中部時95% [================================================> ] 343,045 17.9K/s eta(英國中部時100%[===================================================>] 358,772 17.6K/s eta(英國中部時100%[===================================================>] 358,772 17.6K/s in 20s 2017-09-16 23:35:40 (17.6 KB/s) - 已保存 “inotify-tools-3.14.tar.gz” [358772/358772]) 編譯安裝 [[email protected] inotify-tools-3.14]# ./configure &&make &&make install checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... /bin/mkdir -p checking for gawk... gawk checking whether make sets $(MAKE)... yes checking whether make sets $(MAKE)... (cached) yes checking for gcc... gcc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking for style of include used by ...... test -z "/usr/local/share/man/man1" || /bin/mkdir -p "/usr/local/share/man/man1" /usr/bin/install -c -m 644 inotifywait.1 inotifywatch.1 ‘/usr/local/share/man/man1‘ make[2]: Leaving directory `/usr/install/inotify-tools-3.14/man‘ make[1]: Leaving directory `/usr/install/inotify-tools-3.14/man‘ make[1]: Entering directory `/usr/install/inotify-tools-3.14‘ make[2]: Entering directory `/usr/install/inotify-tools-3.14‘ make[2]: Nothing to be done for `install-exec-am‘. make[2]: Nothing to be done for `install-data-am‘. make[2]: Leaving directory `/usr/install/inotify-tools-3.14‘ make[1]: Leaving directory `/usr/install/inotify-tools-3.14‘ 安裝成功 將 /usr/local/bin/inotifywait等 相關命令加入系統環境變量或者通過軟鏈接到/usr/bin/ [[email protected] inotify-tools-3.14]# ln -s /usr/local/bin/* /usr/bin/ [[email protected] inotify-tools-3.14]# inotifywait OK成功
實時監控備份腳本
#/bin/bash LocalPath=/data/ [email protected]:/databin/ inotifywait -mrq -e modify,delete,create,attrib ${LocalPath} | while read D E F do /usr/bin/rsync -ahqzt --delete ${LocalPath} $RemotrHost done
測試結果:
[[email protected] server]# sh rsync.sh 另開一個終端 [[email protected] data]# ls 10.txt 1.txt 3.txt 5.txt 7.txt 9.txt winner.txt [[email protected] data]# touch {11,12,13,15}.txt [[email protected] data]# echo "rsync+inotify-tool"> {1,3,5}.txt -bash: {1,3,5}.txt: ambiguous redirect [[email protected] data]# echo "rsync+inotify-tool"> 1.txt [[email protected] data]# echo "rsync+inotify-tool"> 2.txt [[email protected] data]# 129主機檢查同步情況 [[email protected] inotify-tools-3.14]# cd /datab databack/ databin/ [[email protected] inotify-tools-3.14]# cd /databack/rsyncback/ [[email protected] rsyncback]# ls 10.txt 11.txt 12.txt 13.txt 15.txt 1.txt 3.txt 5.txt 7.txt 9.txt winner.txt [[email protected] rsyncback]# cat 1.txt rsync+inotify-tool [[email protected] rsyncback]# cat 3.txt [[email protected] rsyncback]# cat 5.txt [[email protected] rsyncback]# cat 2.txt rsync+inotify-tool [[email protected] rsyncback]#
經過驗證基於系統的文件實時同步是不存在任何問題的,實現了我們初級的需求與規劃,接下可以配置基於rsync用戶的文件實時同步服務。
3、基於rsyncd服務的文件實時同步
數據實時同步規劃(rsync+rsync用戶) | ||||
主機序號 | 主機IP | 備份目錄 | 安裝軟件 | 同步方式 |
1 | 192.168.223.128(數據源服務器) | /data/ | rsync+inotify | 推送 |
2 | 192.168.223.129(備份存儲服務器) | /databack/rsyncback | rsyncd | 一 |
192.168.223.128主機需要安裝rsync+inotify,我們在測試上面的服務時已經安裝,所以不需要再安裝,更改相關的配置即可。192.168.223.129需要安裝和配置rsyncd,而rsync服務是由xinetd服務管理,所以我們需要安裝xinetd服務。
yum install xinetd [[email protected]]# yum install xinetd -y 已加載插件:fastestmirror 設置安裝進程 Loading mirror speeds from cached hostfile * base: mirrors.163.com * extras: mirror.lzu.edu.cn * updates: centos.ustc.edu.cn 包 2:xinetd-2.3.14-40.el6.x86_64 已安裝並且是最新版本 無須任何處理
啟動rsync服務需要更改相關配置
[[email protected] rsyncback]# vi /etc/xinetd.d/rsync # default: off # description: The rsync server is a good addition to an ftp server, as it # allows crc checksumming etc. service rsync { disable = no #將這裏的yes更改為no flags = IPv6 socket_type = stream wait = no user = root server = /usr/bin/rsync server_args = --daemon log_on_failure += USERID } 啟動服務 [[email protected] rsyncback]# /etc/init.d/xinetd restart 停止 xinetd: [失敗] 正在啟動 xinetd: [確定] 或者以下方式 [[email protected] rsyncback]# rsync --daemon --config=/etc/rsyncd.conf Failed to parse config file: /etc/rsyncd.conf 默認情況下/etc/rsyncd.conf該文件不存在需要我們手動去創建
創建rsyncd.conf文件 以及其相關介紹
uid =nobody #運行進程的身份 gid =nobody #運行進程的組 address =192.168.223.129 #監聽IP port =873 #監聽端口 hosts allow =192.168.223.128 #允許同步客戶端的IP地址,可以是網段,或者用*表示所有 192.168.1.0/24或192.168.1.0/255.255.255.0 use chroot =yes #是否囚牢,鎖定家目錄,rsync被黑之後,黑客無法再rsync運行的家目錄之外創建文件,選項設置為yes max connections =5 #最大連接數 pid file =/var/run/rsyncd.pid #進程PID,自動生成 lock file =/var/run/rsync.lock #指max connectios參數的鎖文件 log file =/var/log/rsyncd.log #日誌文件位置 motd file =/etc/rsyncd.motd #客戶端登陸之後彈出的消息,需要創建 [databack] #共享模塊名稱 path =/databack/rsyncback #路徑 comment =used for web-data root #描述 readonly = yes #只讀方式(只可以下載) list =yes #是否允許查看模塊信息 auth users = rsyncuser #備份的用戶,和系統用戶無關 secrets file =/etc/rsync.passwd #存放用戶的密碼文件,格式是 用戶名:密碼 創建提示文件和用戶密碼 [[email protected] rsyncback]# vi /etc/rsync.passwd rsyncuser:password123 [[email protected] rsyncback]# cat /etc/rsync.passwd rsyncuser:password123 [[email protected] rsyncback]# chmod 600 /etc/rsync.passwd #目錄權限必須是700或者600,否則的話身份驗證會失效,設置rsync user的時候 [[email protected] rsyncback]# 啟動服務測試: [[email protected] rsyncback]# rsync --daemon --config=/etc/rsyncd.conf 或者 [[email protected] rsyncback]# /etc/init.d/xinetd restart [[email protected] rsyncback]# rsync --daemon --config=/etc/rsyncd.conf [[email protected] rsyncback]# netstat -antup | grep :873 tcp 0 0 192.168.223.129:873 0.0.0.0:* LISTEN 7299/rsync
測試文件同步服務(192.168.223.128上面推送)
[[email protected] data]# rsync -azp /data/ [email protected]::databack Welcome to Backup Server Password: #輸入密碼password123 [[email protected] data]# ls 10.txt DIR_COLORS init.conf mtab securetty 11.txt DIR_COLORS.256color inittab my.cnf services 12.txt DIR_COLORS.lightbgcolor inputrc my.cnf.rpmnew sestatus.conf 13.txt dracut.conf issue networks shadow 15.txt environment issue.net nsswitch.conf shadow- 1.txt ethers kdump.conf passwd shells 2.txt exports krb5.conf passwd- statetab 3.txt favicon.png ld.so.cache printcap sudo.conf 5.txt filesystems ld.so.conf profile sudoers 7.txt fstab libaudit.conf protocols sudo-ldap.conf 9.txt gai.conf libuser.conf rc sysctl.conf adjtime group localtime rc.local system-release aliases group- login.defs rc.sysinit system-release-cpe aliases.db grub.conf logrotate.conf redhat-release virc asound.conf gshadow magic resolv.conf wgetrc bashrc gshadow- mailcap rpc winner.txt centos-release host.conf man.config rsyncd.conf xinetd.conf crypttab hosts mime.types rsyncd.secrets yum.conf csh.cshrc hosts.allow mke2fs.conf rsyslog.conf csh.login hosts.deny motd rwtab 192.168.223.129主機上檢查推送結果 [[email protected] rsyncback]# ls 10.txt DIR_COLORS init.conf mtab securetty 11.txt DIR_COLORS.256color inittab my.cnf services 12.txt DIR_COLORS.lightbgcolor inputrc my.cnf.rpmnew sestatus.conf 13.txt dracut.conf issue networks shadow 15.txt environment issue.net nsswitch.conf shadow- 1.txt ethers kdump.conf passwd shells 2.txt exports krb5.conf passwd- statetab 3.txt favicon.png ld.so.cache printcap sudo.conf 5.txt filesystems ld.so.conf profile sudoers 7.txt fstab libaudit.conf protocols sudo-ldap.conf 9.txt gai.conf libuser.conf rc sysctl.conf adjtime group localtime rc.local system-release aliases group- login.defs rc.sysinit system-release-cpe aliases.db grub.conf logrotate.conf redhat-release virc asound.conf gshadow magic resolv.conf wgetrc bashrc gshadow- mailcap rpc winner.txt centos-release host.conf man.config rsyncd.conf xinetd.conf crypttab hosts mime.types rsyncd.secrets yum.conf csh.cshrc hosts.allow mke2fs.conf rsyslog.conf csh.login hosts.deny motd rwtab 刪除192.168.223.128下/data數據
實時同步測試
客戶端創建密碼文件 (192.168.223.128)
[[email protected] data]# vi /etc/rsync_client.pwd password123 更改權限 [[email protected] data]# chmod 600 /etc/rsync_client.pwd 執行以下命令 [[email protected] data]# rsync -azP --delete --password-file=/etc/rsync_client.pwd /data/ [email protected]::databack 這時候客戶端就不需要輸入密碼了 編寫實時監控同步腳本 #/bin/bash LocalPath=/data/ [email protected]:/databack/rsyncback/ #inotifywait -mrq -e create,move,delete,modify /data/bin* inotifywait -mrq -e modify,delete,create,attrib ${LocalPath} | while read D E F do rsync -azP --delete --password-file=/etc/rsync_client.pwd /data/ [email protected]::databack done 執行腳本
[[email protected] server]# sh -x rsyncinotify.sh 另一個中端執行cp /etc/* /data/ total size is 838095 speedup is 591.88 + read D E F + rsync -azP --delete --password-file=/etc/rsync_client.pwd /data/ [email protected]::databack Welcome to Backup Server sending incremental file list sent 1408 bytes received 8 bytes 944.00 bytes/sec total size is 838095 speedup is 591.88 + read D E F + rsync -azP --delete --password-file=/etc/rsync_client.pwd /data/ [email protected]::databack Welcome to Backup Server sending incremental file list sent 1408 bytes received 8 bytes 2832.00 bytes/sec total size is 838095 speedup is 591.88 + read D E F + rsync -azP --delete --password-file=/etc/rsync_client.pwd /data/ [email protected]::databack
192.168.223.129 主機的數據情況
[[email protected] rsyncback]# ls adjtime init.conf protocols aliases inittab rc aliases.db inputrc rc.local asound.conf issue rc.sysinit bashrc issue.net redhat-release centos-release kdump.conf resolv.conf crypttab krb5.conf rpc csh.cshrc ld.so.cache rsync_client.pwd csh.login ld.so.conf rsyncd.conf DIR_COLORS libaudit.conf rsyncd.secrets DIR_COLORS.256color libuser.conf rsyslog.conf DIR_COLORS.lightbgcolor localtime rwtab dracut.conf login.defs securetty environment logrotate.conf services ethers magic sestatus.conf exports mailcap shadow favicon.png man.config shadow- filesystems mime.types shells fstab mke2fs.conf statetab gai.conf motd sudo.conf group mtab sudoers group- my.cnf sudo-ldap.conf grub.conf my.cnf.rpmnew sysctl.conf gshadow networks system-release gshadow- nsswitch.conf system-release-cpe host.conf passwd virc hosts passwd- wgetrc hosts.allow printcap xinetd.conf hosts.deny profile yum.conf [[email protected] rsyncback]# ls |wc 87 87 888 刪除同步: [[email protected] data]# rm -f ./* [[email protected] data]# [[email protected] rsyncback]# ls #結果為空 [[email protected] rsyncback]#
到這裏基礎的數據同步基本上做完,但是忽略部分數據以及腳本日誌信息還需要繼續完善,後期持續完善!
本文出自 “堅持夢想” 博客,請務必保留此出處http://dreamlinux.blog.51cto.com/9079323/1965970
Rsync+inotify實現文件實時同步