1、Linux文件同步工具-rsync
安装:yum install -y rsync
- rsync -av /etc/passwd /tmp/1.txt 本地同步
- rsync -av /tmp/1.txt 192.168.188.128:/tmp/2.txt 远程同步
rsync格式
- rsync [OPTION] … SRC(源目录) DEST(目的目录)
- rsync [OPTION] … SRC [user@]host:DEST (到远程的服务器;user@可省略,会默认为当前终端的用户)
- rsync [OPTION] … [user@]host:SRC DEST (先写远程的机器/目录,然后同步到本地的目录下)
- rsync [OPTION] … SRC [user@]host::DEST (两个冒号,可以是目标,可以是源)
- rsync [OPTION] … [user@]host::SRC DEST
1.2、rsync常用选项
- -a 归档模式,以递归方式传输文件,并保持文件所有属性;包含-rtplgoD参数选项
- -r 同步目录时要加上,类似cp时的-r选项
- -v 同步时显示一些信息,让我们知道同步的过程
- -l 保留软连接(若是拷贝的原目录里面有一个软链接文件,那这个软链接文件指向到了另外一个目录下;在加上-l,它会把软链接文件本身拷贝到目标目录里面去)
- -L 加上该选项后,同步软链接时会把源文件给同步
- -p 保持文件的权限属性
- -o 保持文件的属主
- -g 保持文件的属组
- -D 保持设备文件信息(/dev/sdb1 这样的设备文件有它的特殊性,如果不加-D 可能拷贝过去就是一个非常普通的文件,不能当设备来用)
- -t 保持文件的时间属性
- --delete 删除DEST中SRC没有的文件
- --exclude 过滤指定文件,也可这样使用--exclude=“过滤文件”;如--exclude “logs”会把文件名包含logs的文件或者目录过滤掉,不同步
- -P 显示同步过程,比如速率,比-v更加详细
- -u 加上该选项后,如果DEST中的文件比SRC新,则不同步
- update
- -z 传输时压缩
常用选项:-a、-v、-z、--delete、--exclude
实验:
- 创建目录和文件
[root@localhost ~]# mkdir rsync
[root@localhost ~]# cd rsync
[root@localhost rsync]# mkdir test1
[root@localhost rsync]# touch 1 2 3 /root/123.txt
[root@localhost rsync]# ln -s /root/123.txt ./123.txt
[root@localhost rsync]# ls -l
总用量 0
-rw-r--r--. 1 root root 0 6月 16 13:16 1
lrwxrwxrwx. 1 root root 13 6月 16 13:17 123.txt -> /root/123.txt
-rw-r--r--. 1 root root 0 6月 16 13:16 2
-rw-r--r--. 1 root root 0 6月 16 13:16 3
drwxr-xr-x. 2 root root 6 6月 16 13:15 test1
1.2.1、-a选项
[root@aminglinux rsync]# rsync -a test1 test2
[root@aminglinux rsync]# ls test2
test1
[root@aminglinux rsync]# ls test2/test1
1 123.txt 2 3
想法:把test1复制到test2;目录不加“/”,则变成创建了test2目录,再把test1放到test2目录中;与想法不符;需在目录加“/”;
[root@aminglinux rsync]# rm -rf test2
[root@aminglinux rsync]# rsync -a test1/ test2/
[root@aminglinux rsync]# ls -l test2/
总用量 0
-rw-r--r-- 1 root root 0 6月 16 13:28 1
lrwxrwxrwx 1 root root 13 6月 16 13:28 123.txt -> /root/123.txt
-rw-r--r-- 1 root root 0 6月 16 13:28 2
-rw-r--r-- 1 root root 0 6月 16 13:28 3
-a和--no-OPTIN一起使用(-a选项等同于-rlptgoD;--no-OPTIN等于去掉-rlptgoD中的选项)
[root@aminglinux rsync]# rm -rf test2
[root@aminglinux rsync]# rsync -av --no-l test1/ test2/
sending incremental file list
created directory test2
skipping non-regular file "123.txt"
./
1
2
3
sent 234 bytes received 144 bytes 756.00 bytes/sec
total size is 13 speedup is 0.03
1.2.2、-L选项:把SRC中软链接的源文件复制到DEST;
[root@aminglinux rsync]# rm -rf test2
[root@aminglinux rsync]# rsync -avL test1/ test2/
sending incremental file list
created directory test2
./
1
123.txt
2
3
sent 265 bytes received 123 bytes 776.00 bytes/sec
total size is 0 speedup is 0.00
1.2.3、--delete选项:删除DEST中SRC没有的文件