1,338 瀏覽數

Linux command – rsync

測試環境為 Ubuntu16.04 x64 虛擬機.

發現之前用 wordpress 時,其中一個步驟會用到 rsync ,查了一下以前自己的文章也有用過 rsync .

root@ubuntu:~# wget http://wordpress.org/latest.tar.gz
root@ubuntu:~# tar xzvf latest.tar.gz

將文件複製到目錄 /var/www/html/ (Nginx 預設的根目錄)

RSYNC COMMAND

root@ubuntu:~# rsync -avP ~/wordpress/ /var/www/html/
....
sent 23,449,511 bytes  received 29,044 bytes  9,391,422.00 bytes/sec
total size is 23,343,039  speedup is 0.99

參數

  • -a, –archive archive mode; equals -rlptgoD (no -H,-A,-X)
    • -r, –recursive recurse into directories
    • -l, –links copy symlinks as symlinks
    • -p, –perms preserve permissions
    • -t, –times preserve modification times
    • -g, –group preserve group
    • -o, –owner preserve owner (super-user only)
    • -D same as –devices (This option causes rsync to transfer character and block device files to the remote system to recreate these devices. ) –specials (This option causes rsync to transfer special files such as named sockets and fifos)
  • -v, –verbose increase verbosity
  • -P same as –partial(keep partially transferred files) –progress(show progress during transfer)

相同的資料夾再複製一次,可以發現 rsync 實際上並沒再一次複製檔案到目地端.剛剛第一次複製檔案時,rsync 會將完整的檔案內容複製到目地端,第二次複製檔案時,會用先演算法檢查來源端與目的端檔案的差異,並傳送有差異的部份.

root@ubuntu:~# rsync -avP ~/wordpress/ /var/www/html/
sending incremental file list

sent 39,037 bytes  received 153 bytes  78,380.00 bytes/sec
total size is 23,343,039  speedup is 595.64

RSYNC 遠端備份

除了本地端外,遠端的資料夾一樣可以透過 rsync 來同步.

Local:  rsync [OPTION...] SRC... [DEST]

如同 scp 一樣 rsync 可以透過遠端的方式做資料同步的動作,使用的協定 protocol 為 SSH (遠端需開啟 SSH 服務).

Access via remote shell:
Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST]
Push: rsync [OPTION...] SRC... [USER@]HOST:DEST
root@ubuntu:~# rsync -avP /root/wordpress/ ben@172.16.15.249:/home/ben/Desktop/
The authenticity of host '172.16.15.249 (172.16.15.249)' can't be established.
ECDSA key fingerprint is SHA256:qRW5nzrgHLRzNj37o1EJtOt8/+2/o/c87aSc5JcquGE.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.15.249' (ECDSA) to the list of known hosts.
ben@172.16.15.249's password:

RSYNC Exclude

參數

  • –exclude=PATTERN
    This option is a simplified form of the –filter option that defaults to an exclude rule and does not allow the full rule-parsing syntax of normal filter rules.

Exclude 可以針對定檔案名稱.

root@ubuntu:~# rsync -avP --exclude *.php ~/wordpress/ /var/www/html/

Exclude 也可以針對定路徑名稱.

root@ubuntu:~# rsync -avP --exclude wp-admin/ ~/wordpress/ /var/www/html/

RSYNC Daemon

如果是要定時同步來源端與目的端檔案時,可以透過設定 rsyncd 服務,範例檔位於 /usr/share/doc/rsync/examples/rsyncd.conf ,複製至 /etc/rsyncd.conf ,並修改內容,啟動 rsyncd 的服務.

root@ubuntu:~# cp /usr/share/doc/rsync/examples/rsyncd.conf /etc/
root@ubuntu:~# systemctl start rsync
root@ubuntu:~# systemctl enable rsync
Synchronizing state of rsync.service with SysV init with /lib/systemd/systemd-sysv-install...
Executing /lib/systemd/systemd-sysv-install enable rsync

詳細設定請參考 http://benjr.tw/99075

發表迴響