1,135 瀏覽數

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 預設的根目錄)

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 與 scp 一樣可以透過遠端的方式做資料同步的動作.

root@ubuntu:~# rsync -avP /root/wordpress/ ben@172.16.15.130:/home/ben/Desktop/
ben@172.16.15.130's password: 
...
sent 23,449,507 bytes  received 29,092 bytes  1,341,634.23 bytes/sec
total size is 23,343,039  speedup is 0.99

如果是要定時同步來源端與目的端檔案時,可以透過設定 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

發表迴響