Rsync表明"remote sync",它是本地和遠程主機文件同步工具。它只同步更改的文件,以此實現最小化傳輸數據。rsync的使用場景很是豐富,相信你們會常用,這裏作下簡單的總結。html
rsync安裝配置實踐
2019年03月01日 - 初稿python
閱讀原文 - https://wsgzao.github.io/post...linux
擴展閱讀nginx
rsync - https://www.samba.org/rsync/git
rsync is a file transfer program capable of efficient remote update via a fast differencing algorithm.github
rsync 是類 unix 系統下的數據鏡像備份工具,從軟件的命名上就能夠看出來了 ——remote sync。它的特性以下:shell
在使用 rsync 進行遠程同步時,可使用兩種方式:遠程 Shell 方式(用戶驗證由 ssh 負責)和 C/S 方式(即客戶鏈接遠程 rsync 服務器,用戶驗證由 rsync 服務器負責)。vim
不管本地同步目錄仍是遠程同步數據,首次運行時將會把所有文件拷貝一次,之後再運行時將只拷貝有變化的文件(對於新文件)或文件的變化部分(對於原有文件)。安全
# 編輯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/rsy...bash
注: 在指定複製源時,路徑是否有最後的 「/」 有不一樣的含義,例如:
/data 表示將整個 /data 目錄複製到目標目錄
/data/ 表示將 /data/ 目錄中的全部內容複製到目標目錄
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經常使用參數 -v :展現詳細的同步信息 -a :歸檔模式,至關於 -rlptgoD -r :遞歸目錄 -l :同步軟鏈接文件 -p :保留權限 -t :將源文件的"modify time"同步到目標機器 -g :保持文件屬組 -o :保持文件屬主 -D :和--devices --specials同樣,保持設備文件和特殊文件 -z :發送數據前,先壓縮再傳輸 -H :保持硬連接 -n :進行試運行,不做任何更改 -P same as --partial --progress --partial :支持斷點續傳 --progress :展現傳輸的進度 --delete :若是源文件消失,目標文件也會被刪除 --delete-excluded :指定要在目的端刪除的文件 --delete-after :默認狀況下,rsync是先清理目的端的文件再開始數據同步;若是使用此選項,則rsync會先進行數據同步,都完成後再刪除那些須要清理的文件。 --exclude=PATTERN :排除匹配PATTERN的文件 --exclude-from=FILE :若是要排除的文件不少,能夠統一寫在某一文件中 -e ssh :使用SSH加密隧道傳輸 # 遠程Shell方式 rsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST # 執行「推」操做 or rsync [OPTION]... [USER@]HOST:SRC [DEST] # 執行「拉」操做 # 遠程C/S方式 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]... rsync://[USER@]HOST[:PORT]/SRC [DEST] # 執行「拉」操做
Rsync 遠程同步主要有兩種方式:使用遠程 shell(ssh或rsh) 或使用 rsync 的 daemon 方式
rsync 命令和 ssh,scp 命令有點類似。
咱們建立兩個測試目錄和一些文件:
mkdir dir1 mkdir dir2 touch dir1/somefile{1..100} # dir1 中有 100 文件,dir2 中爲空。使用 rsync 把 dir1 內容同步到 dir2,-r 選項表明遞歸,在同步目錄時使用。 rsync -r dir1/ dir2 # 你也可使用 -a 選項,表明同步全部,包括修改時間、羣組、權限、特殊文件、也包括遞歸。 rsync -anv dir1/ dir2 # 注意上面的 dir1 / 中的 「/」 不能少,它表明同步目錄下文件, 若是沒有 「/」 表明同步這個目錄。 # 和遠程主機進行同步目錄首先,你要確保有遠程主機的 SSH 訪問權限 # 把本地目錄同步到遠程主機: rsync -a dir1/ root@linux:~/dir2 # 把遠程主機目錄同步到本地: rsync -a root@linux:~/dir2/ dir1
# 若是沒有desc目錄,會自動建立 rsync -avH /opt/resource/ /tmp/desc/
# 從本地傳到遠端,目標文件會被寫成ssh登陸用戶的屬組和屬主(以下 www) rsync -avH /opt/nginx-1.12.1/ www@172.18.50.125:/tmp/nginx/ # 使用 ssh 加密隧道方式傳輸,保障數據的安全性 rsync -avHe ssh /opt/nginx-1.12.1/ www@172.18.50.125:/tmp/nginx/ # 從遠端傳到本地,只要對目標文件有讀的權限,就能夠同步到本地 rsync -avH www@172.18.50.125:/tmp/nginx/ /tmp/nginx/ # 若是遠程服務器ssh端口不是默認的22 rsync -avHe "ssh -p 11222" /opt/nginx-1.12.1/ www@172.18.50.125:/tmp/nginx/
rsync服務端配置
# 建立 rsync 服務的目錄和配置文件 (可選) 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. # 傳輸文件使用的用戶和用戶組,若是是從服務器=>客戶端,要保證www用戶對文件有讀取的權限;若是是從客戶端=>服務端,要保證www對文件有寫權限。 uid = www gid = www # 容許chroot,提高安全性,客戶端鏈接模塊,首先chroot到模塊path參數指定的目錄下,chroot爲yes時必須使用root權限,且不能備份path路徑外的連接文件 use chroot = yes # 只讀 read only = no # 只寫 write only = no # 設定白名單,能夠指定IP段(172.18.50.1/255.255.255.0),各個Ip段用空格分開 hosts allow = 172.18.50.110 172.18.50.111 hosts deny = * # 容許的客戶端最大鏈接數 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/ # 設置超時時間 timeout = 900 ignore nonreadable = yes # 設置不須要壓縮的文件 dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2 # 模塊,能夠配置多個,使用如: sate@172.18.50.125::125to110 [125to110] # 模塊的根目錄,同步目錄,要注意權限 path = /tmp/nginx # 是否容許列出模塊內容 list = no # 忽略錯誤 ignore errors # 添加註釋 comment = ftp export area # 模塊驗證的用戶名稱,可以使用空格或者逗號隔開多個用戶名 auth users = sate # 模塊驗證密碼文件 可放在全局配置裏 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客戶端配置
# 從 服務端 => 客戶端 同步數據,會提示輸入密碼 rsync -avzP --delete sate@172.18.50.125::125to110 /tmp/sync/ # 從 客戶端 => 服務端 同步數據,會提示輸入密碼 rsync -avzP --delete /tmp/sync/ sate@172.18.50.125::125to110 # 注: 若是是 /tmp/sync,則同步sync目錄;若是 /tmp/sync/,則同步sync目錄下的文件 # 免密碼同步,將密碼寫到文件,再經過 --password-file 指定該文件,注:該文件的權限必須是 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 排除文件目錄時,若是有多個同名目錄的狀況 # 目錄結構 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 # 會發現,該目錄下全部 test 目錄都被排除了,若是想只排除第一層目錄的 test,能夠以下(/ 表明所同步目錄第一層): rsync -avP --delete --password-file=/tmp/secrets.file --exclude=/test/ /tmp/sync/ sate@172.18.50.125::125to110 # 狀況二 : 和狀況一不一樣的是 同步的 /tmp/sync 這個目錄(同步的是/tmp/sync 目錄自己,致使 exclude 後邊的參數也會變化) rsync -avP --delete --password-file=/tmp/secrets.file --exclude=/sync/test/ /tmp/sync sate@172.18.50.125::125to110
# 配置服務端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 # 設置服務 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)
-z 選項,壓縮傳輸的文件
rsync -az source dest
-P 選項很是有用,它是 -progress 和 -partial 的組合。第一個選項是用來顯示傳輸進度條,第二個選項容許斷點續傳和增量傳輸:
rsync -azP source dest
--bwlimit選項,限制傳輸帶寬,參數值的默認單位是 KBPS,也就是每秒多少 KB
rsync -avzP --bwlimit=100