rsync工具介紹
使用場景:A機器傳輸檔案到B機器。或者備份資料到遠端機器。本機的A目錄到B目錄,其中A目錄資料不斷的增加,每小時備份到B機器。使用cp顯然不合适。
•rsync -av /etc/passwd /tmp/1.txt //-a 保含了好幾個選項
• rsync格式
本地目錄 目标目錄
• rsync [OPTION] … SRC DEST
• rsync [OPTION] … SRC [user@]host:DEST
rsync -av /tmp/1.txt [email protected]:/tmp/2.txt //不寫使用者就是目前的使用者,對方機器沒有會報錯
• rsync [OPTION] … [user@]host:SRC DEST //遠端目錄拷貝到本地目錄下
• rsync [OPTION] … SRC [user@]host::DEST //::可以是目标也可以是源
• rsync [OPTION] … [user@]host::SRC DEST
•rsync常用選項
• -a 包含-rtplgoD
• -r 同步目錄時要加上,類似cp時的-r選項
• -v 同步時顯示一些資訊,讓我們知道同步的過程
• -l 保留軟連接配接
• -L 加上該選項後,同步軟連結時會把源檔案給同步
• -p 保持檔案的權限屬性
• -o 保持檔案的屬主 //如果對方沒有就顯示數字
• -g 保持檔案的屬組
• -D 保持裝置檔案資訊
• -t 保持檔案的時間屬性
--delete 删除DEST中SRC沒有的檔案
--exclude 過濾指定檔案,如--exclude “logs”
•-P 顯示同步過程,比如速率,比-v更加詳細
-u (update)加上該選項後,如果DEST中的檔案比SRC新,則不同步。
•-z 傳輸時壓縮
rsync常用選項(下)
測試:
rsync -av /root/lsx/ /tmp/lsx_dest/ //不加L的情況。同步目錄後面加/。加/表示把目錄的内容同步過來。不加/就是把目錄和内容一起同步過來。
ll /tmp/lsx_dest/
lrwxrwxrwx 1 root root 12 11月 30 23:53 123.txt -> /tmp/123.txt
lrwxrwxrwx 1 root root 11 11月 30 23:44 12.txt -> /tmp/12.txt
[root@localhost ~]# rsync -avL /root/lsx/ /tmp/lsx_dest/ //加L的就相當于沒有小l。會把源檔案内容拷貝過去
-rw-r--r-- 1 root root 9 11月 30 23:52 123.txt
2.--delete
-rw-r--r-- 1 root root 6 11月 30 23:39 1.txt
-rw-r--r-- 1 root root 0 12月 1 00:11 new.txt
[root@localhost ~]# rsync -av --delete /root/lsx/ /tmp/lsx_dest/ //加--delete把目标檔案中src沒有的檔案删除(如果是做鏡像備份就需要加)
sending incremental file list
deleting new.txt
cat /tmp/lsx_dest/1.txt
dadad
123
rsync -avu /root/lsx/ /tmp/lsx_dest/ //加u的情況
./
4.--exclude
rsync -av --exclude ".txt" /root/lsx/ /tmp/lsx_dest/ //--exclude過濾txt檔案。支援連續多個格式 --exclude ".txt" --exclude "."
passwd
ls /tmp/lsx_dest/
ls /root/lsx/
123.txt 12.txt 1.txt passwd
5.-P
rsync -avP --exclude "*.txt" /root/lsx/ /tmp/lsx_dest/ //-P可以看到傳輸過程幾兆每秒(是否卡死)
883 100% 0.00kB/s 0:00:00 (xfer#1, to-check=0/2)
sent 974 bytes received 34 bytes 2016.00 bytes/sec
total size is 883 speedup is 0.88
通過ssh同步
A機器到B機器。
rsync通過ssh方式同步
rsync -av test1/ 192.168.133.132:/tmp/test2/ //把test1目錄同步到另外一台機器
rsync /etc/passwd 192.168.211.149:/root/ //推檔案。拉
The authenticity of host '192.168.211.149 (192.168.211.149)' can't be established.
ECDSA key fingerprint is 0f:bd:8f:21:d3:48:a7:6c:f0:ae:00:b4:56:9e:c7:da.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.211.149' (ECDSA) to the list of known hosts.
[email protected]'s password:
bash: rsync: 未找到指令
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: remote command not found (code 127) at io.c(605) [sender=3.0.9]
原因是機器預設是沒有rsync指令的。是以要在另外一台機器安裝rsync
rsync -avz 192.168.211.149:/root/passwd /tmp/passwd //拉檔案
!!如果對方端口不是22
rsync -avz -e "ssh -p 22" 192.168.211.149:/root/passwd /tmp/passwd
receiving incremental file list
sent 11 bytes received 36 bytes 18.80 bytes/sec
total size is 883 speedup is 18.79
ssh -p 22 192.168.211.149 //這種方式可以直接登入到對方機器
本文轉自 蝦米的春天 51CTO部落格,原文連結:http://blog.51cto.com/lsxme/2047434,如需轉載請自行聯系原作者