前言
Rsync代表"remote sync",它是本地和遠(yuǎn)程主機(jī)文件同步工具盐肃。它只同步更改的文件,以此實(shí)現(xiàn)最小化傳輸數(shù)據(jù)权悟。rsync的使用場景非常豐富砸王,相信大家會經(jīng)常使用,這里做下簡單的總結(jié)峦阁。
rsync安裝配置實(shí)踐
更新歷史
2019年03月01日 - 初稿
閱讀原文 - https://wsgzao.github.io/post/rsync/
擴(kuò)展閱讀
rsync - https://www.samba.org/rsync/
rsync簡介
rsync is a file transfer program capable of efficient remote update via a fast differencing algorithm.
rsync 是類 unix 系統(tǒng)下的數(shù)據(jù)鏡像備份工具谦铃,從軟件的命名上就可以看出來了 ——remote sync。它的特性如下:
- 可以鏡像保存整個目錄樹和文件系統(tǒng)
- 可以很容易做到保持原來文件的權(quán)限榔昔、時間驹闰、軟硬鏈接等等
- 無須特殊權(quán)限即可安裝
- 優(yōu)化的流程,文件傳輸效率高
- 可以使用 rsh撒会、ssh 等方式來傳輸文件嘹朗,當(dāng)然也可以通過直接的 socket 連接
- 支持匿名傳輸
在使用 rsync 進(jìn)行遠(yuǎn)程同步時,可以使用兩種方式:遠(yuǎn)程 Shell 方式(用戶驗(yàn)證由 ssh 負(fù)責(zé))和 C/S 方式(即客戶連接遠(yuǎn)程 rsync 服務(wù)器诵肛,用戶驗(yàn)證由 rsync 服務(wù)器負(fù)責(zé))屹培。
無論本地同步目錄還是遠(yuǎn)程同步數(shù)據(jù),首次運(yùn)行時將會把全部文件拷貝一次曾掂,以后再運(yùn)行時將只拷貝有變化的文件(對于新文件)或文件的變化部分(對于原有文件)惫谤。
rsync源配置文件示例
# 編輯rsync配置文件
vim /etc/rsync.conf
# /etc/rsyncd: configuration file for rsync daemon mode
# See rsyncd.conf man page for more options.
# configuration example:
# uid = nobody
# gid = nobody
# use chroot = yes
# max connections = 4
# pid file = /var/run/rsyncd.pid
# exclude = lost+found/
# transfer logging = yes
# timeout = 900
# ignore nonreadable = yes
# dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
# [ftp]
# path = /home/ftp
# comment = ftp export area
rsyncd.conf 官方文檔請參考
https://www.samba.org/ftp/rsync/rsyncd.conf.html
rsync常用參數(shù)
注: 在指定復(fù)制源時壁顶,路徑是否有最后的 “/” 有不同的含義珠洗,例如:
/data 表示將整個 /data 目錄復(fù)制到目標(biāo)目錄
/data/ 表示將 /data/ 目錄中的所有內(nèi)容復(fù)制到目標(biāo)目錄
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]... [USER@]HOST:DEST
or rsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST
or rsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DEST
or rsync [OPTION]... [USER@]HOST:SRC [DEST]
or rsync [OPTION]... [USER@]HOST::SRC [DEST]
or rsync [OPTION]... rsync://[USER@]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
--info=FLAGS fine-grained informational verbosity
--debug=FLAGS fine-grained debug verbosity
--msgs2stderr special output handling for debugging
-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
--munge-links munge symlinks to make them safer (but unusable)
-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
-J, --omit-link-times omit symlinks from --times
--super receiver attempts super-user activities
--fake-super store/recover privileged attrs using xattrs
-S, --sparse handle sparse files efficiently
--preallocate allocate dest files before writing them
-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 the transfer
--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-missing-args ignore missing source args without error
--delete-missing-args delete missing source args from destination
--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
--usermap=STRING custom username mapping
--groupmap=STRING custom groupname mapping
--chown=USER:GROUP simple username/groupname mapping
--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
-M, --remote-option=OPTION send OPTION to the remote side only
--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=RATE limit socket I/O bandwidth
--outbuf=N|L|B set output buffering to None, Line, or Block
--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
--checksum-seed=NUM set block/file checksum seed (advanced)
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
--version print version number
(-h) --help show this help (-h is --help only if used alone)
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
# rsync常用參數(shù)
-v :展示詳細(xì)的同步信息
-a :歸檔模式,相當(dāng)于 -rlptgoD
-r :遞歸目錄
-l :同步軟連接文件
-p :保留權(quán)限
-t :將源文件的"modify time"同步到目標(biāo)機(jī)器
-g :保持文件屬組
-o :保持文件屬主
-D :和--devices --specials一樣若专,保持設(shè)備文件和特殊文件
-z :發(fā)送數(shù)據(jù)前许蓖,先壓縮再傳輸
-H :保持硬鏈接
-n :進(jìn)行試運(yùn)行,不作任何更改
-P same as --partial --progress
--partial :支持?jǐn)帱c(diǎn)續(xù)傳
--progress :展示傳輸?shù)倪M(jìn)度
--delete :如果源文件消失,目標(biāo)文件也會被刪除
--delete-excluded :指定要在目的端刪除的文件
--delete-after :默認(rèn)情況下膊爪,rsync是先清理目的端的文件再開始數(shù)據(jù)同步自阱;如果使用此選項,則rsync會先進(jìn)行數(shù)據(jù)同步米酬,都完成后再刪除那些需要清理的文件沛豌。
--exclude=PATTERN :排除匹配PATTERN的文件
--exclude-from=FILE :如果要排除的文件很多,可以統(tǒng)一寫在某一文件中
-e ssh :使用SSH加密隧道傳輸
# 遠(yuǎn)程Shell方式
rsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST # 執(zhí)行“推”操作
or rsync [OPTION]... [USER@]HOST:SRC [DEST] # 執(zhí)行“拉”操作
# 遠(yuǎn)程C/S方式
rsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST # 執(zhí)行“推”操作
or rsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DEST # 執(zhí)行“推”操作
or rsync [OPTION]... [USER@]HOST::SRC [DEST] # 執(zhí)行“拉”操作
or rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST] # 執(zhí)行“拉”操作
rsync同步方式
Rsync 遠(yuǎn)程同步主要有兩種方式:使用遠(yuǎn)程 shell(ssh或rsh) 或使用 rsync 的 daemon 方式
rsync 命令和 ssh赃额,scp 命令有點(diǎn)相似加派。
我們創(chuàng)建兩個測試目錄和一些文件:
mkdir dir1
mkdir dir2
touch dir1/somefile{1..100}
# dir1 中有 100 文件,dir2 中為空跳芳。使用 rsync 把 dir1 內(nèi)容同步到 dir2芍锦,-r 選項代表遞歸,在同步目錄時使用飞盆。
rsync -r dir1/ dir2
# 你也可以使用 -a 選項娄琉,代表同步所有,包括修改時間吓歇、群組孽水、權(quán)限、特殊文件照瘾、也包括遞歸匈棘。
rsync -anv dir1/ dir2
# 注意上面的 dir1 / 中的 “/” 不能少,它代表同步目錄下文件析命, 如果沒有 “/” 代表同步這個目錄主卫。
# 和遠(yuǎn)程主機(jī)進(jìn)行同步目錄首先,你要確保有遠(yuǎn)程主機(jī)的 SSH 訪問權(quán)限
# 把本地目錄同步到遠(yuǎn)程主機(jī):
rsync -a dir1/ root@linux:~/dir2
# 把遠(yuǎn)程主機(jī)目錄同步到本地:
rsync -a root@linux:~/dir2/ dir1
本地文件同步
# 如果沒有desc目錄鹃愤,會自動創(chuàng)建
rsync -avH /opt/resource/ /tmp/desc/
遠(yuǎn)程文件同步 --shell 方式
# 從本地傳到遠(yuǎn)端簇搅,目標(biāo)文件會被寫成ssh登錄用戶的屬組和屬主(如下 www)
rsync -avH /opt/nginx-1.12.1/ www@172.18.50.125:/tmp/nginx/
# 使用 ssh 加密隧道方式傳輸,保障數(shù)據(jù)的安全性
rsync -avHe ssh /opt/nginx-1.12.1/ www@172.18.50.125:/tmp/nginx/
# 從遠(yuǎn)端傳到本地软吐,只要對目標(biāo)文件有讀的權(quán)限瘩将,就可以同步到本地
rsync -avH www@172.18.50.125:/tmp/nginx/ /tmp/nginx/
# 如果遠(yuǎn)程服務(wù)器ssh端口不是默認(rèn)的22
rsync -avHe "ssh -p 11222" /opt/nginx-1.12.1/ www@172.18.50.125:/tmp/nginx/
遠(yuǎn)程文件同步 --daemon 方式
rsync服務(wù)端配置
# 創(chuàng)建 rsync 服務(wù)的目錄和配置文件 (可選)
mkdir /etc/rsync
cd /etc/rsync
touch rsyncd.conf
touch rsyncd.secrets
touch rsyncd.motd
chmod 600 rsyncd.secrets
### rsyncd.conf 文件的配置
vim /etc/rsync/rsyncd.conf
# /etc/rsyncd: configuration file for rsync daemon mode
# See rsyncd.conf man page for more options.
# 傳輸文件使用的用戶和用戶組,如果是從服務(wù)器=>客戶端凹耙,要保證www用戶對文件有讀取的權(quán)限姿现;如果是從客戶端=>服務(wù)端,要保證www對文件有寫權(quán)限肖抱。
uid = www
gid = www
# 允許chroot备典,提升安全性,客戶端連接模塊意述,首先chroot到模塊path參數(shù)指定的目錄下提佣,chroot為yes時必須使用root權(quán)限吮蛹,且不能備份path路徑外的鏈接文件
use chroot = yes
# 只讀
read only = no
# 只寫
write only = no
# 設(shè)定白名單,可以指定IP段(172.18.50.1/255.255.255.0),各個Ip段用空格分開
hosts allow = 172.18.50.110 172.18.50.111
hosts deny = *
# 允許的客戶端最大連接數(shù)
max connections = 4
# 歡迎文件的路徑拌屏,非必須
motd file = /etc/rsync/rsyncd.motd
# pid文件路徑
pid file = /var/run/rsyncd.pid
# 記錄傳輸文件日志
transfer logging = yes
# 日志文件格式
log format = %t %a %m %f %b
# 指定日志文件
log file = /var/log/rsync.log
# 剔除某些文件或目錄潮针,不同步
exclude = lost+found/
# 設(shè)置超時時間
timeout = 900
ignore nonreadable = yes
# 設(shè)置不需要壓縮的文件
dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
# 模塊,可以配置多個倚喂,使用如: sate@172.18.50.125::125to110
[125to110]
# 模塊的根目錄每篷,同步目錄,要注意權(quán)限
path = /tmp/nginx
# 是否允許列出模塊內(nèi)容
list = no
# 忽略錯誤
ignore errors
# 添加注釋
comment = ftp export area
# 模塊驗(yàn)證的用戶名稱端圈,可使用空格或者逗號隔開多個用戶名
auth users = sate
# 模塊驗(yàn)證密碼文件 可放在全局配置里
secrets file = /etc/rsync/rsyncd.secrets
# 剔除某些文件或目錄雳攘,不同步
exclude = lost+found/ conf/ man/
### rsyncd.secrets 文件的配置
cat rsyncd.secrets
# 用戶名:密碼
sate:111111
### rsync啟動
rsync --daemon --config=/etc/rsync/rsyncd.conf
rsync客戶端配置
# 從 服務(wù)端 => 客戶端 同步數(shù)據(jù),會提示輸入密碼
rsync -avzP --delete sate@172.18.50.125::125to110 /tmp/sync/
# 從 客戶端 => 服務(wù)端 同步數(shù)據(jù)枫笛,會提示輸入密碼
rsync -avzP --delete /tmp/sync/ sate@172.18.50.125::125to110
# 注: 如果是 /tmp/sync吨灭,則同步sync目錄;如果 /tmp/sync/刑巧,則同步sync目錄下的文件
# 免密碼同步喧兄,將密碼寫到文件,再通過 --password-file 指定該文件啊楚,注:該文件的權(quán)限必須是 600
echo "111111" > /tmp/secrets.file
chmod 600 /tmp/secrets.file
rsync -avzP --delete --password-file=/tmp/secrets.file sate@172.18.50.125::125to110 /tmp/sync/
# --exclude 排除文件目錄時吠冤,如果有多個同名目錄的情況
# 目錄結(jié)構(gòu)
tree
.
├── dir1
│ └── test
│ ├── 3.file
│ ├── 4.file
│ └── 5.file
├── dir2
└── test
├── 1.file
├── 2.file
└── 3.file
# 情況一 : 排除 /test 目錄,同步其他目錄(同步的是/tmp/sync/ 下邊的文件)
rsync -avP --delete --password-file=/tmp/secrets.file --exclude=test /tmp/sync/ sate@172.18.50.125::125to110
# 會發(fā)現(xiàn)恭理,該目錄下所有 test 目錄都被排除了拯辙,如果想只排除第一層目錄的 test,可以如下(/ 代表所同步目錄第一層):
rsync -avP --delete --password-file=/tmp/secrets.file --exclude=/test/ /tmp/sync/ sate@172.18.50.125::125to110
# 情況二 : 和情況一不同的是 同步的 /tmp/sync 這個目錄(同步的是/tmp/sync 目錄本身颜价,導(dǎo)致 exclude 后邊的參數(shù)也會變化)
rsync -avP --delete --password-file=/tmp/secrets.file --exclude=/sync/test/ /tmp/sync sate@172.18.50.125::125to110
rsync簡化配置實(shí)踐
# 配置服務(wù)端rsyncd.conf
vim /etc/rsyncd.conf
read only = no
list = yes
uid = root
gid = root
[backup]
path= /data/
hosts allow = 10.71.12.0/23
# 設(shè)置服務(wù)
systemctl start rsyncd
systemctl enable rsyncd
# 配置rsync客戶端
# 編輯backup.sh同步腳本
vim backup.sh
#!/bin/sh
SOURCE=$1
DEST=$2
CMD="rsync -ravz --bwlimit=2000 $1 rsync://{{log_server_ip}}:873/backup/$2"
PROCS=$(pgrep -f "{{log_server_ip}}:873/backup/$2")
if [ "x" != "x$PROCS" ]; then
echo "not finished"
exit
fi
$CMD
# 修改crontab
vim /etc/crontab
15 * * * * root cd /opt/sa_scripts/ && ./backup.sh /var/log/ocha/pos_python_server/ 10.71.12.89/$(date +\%Y-\%m)
rsync 有用的選項
-z 選項涯保,壓縮傳輸?shù)奈募?/p>
rsync -az source dest
-P 選項非常有用,它是 -progress 和 -partial 的組合周伦。第一個選項是用來顯示傳輸進(jìn)度條夕春,第二個選項允許斷點(diǎn)續(xù)傳和增量傳輸:
rsync -azP source dest
--bwlimit選項,限制傳輸帶寬专挪,參數(shù)值的默認(rèn)單位是 KBPS及志,也就是每秒多少 KB
rsync -avzP --bwlimit=100