### 1.RSYNC概述

Rsync是Linux系统下的数据[镜像](https://baike.baidu.com/item/镜像)[备份](https://baike.baidu.com/item/备份)工具，使用快速增量备份工具Remote Sync可以远程同步，可以在不同主机之间进行同步，可实现全量备份与增量备份，保持链接和权限，且采用优化的同步算法，传输前执行压缩，因此非常适合用于架构集中式备份或异地备份等应用。同时Rsync支持本地复制，或者与其他SSH、rsync主机同步。
官方网站：https://rsync.samba.org/



#### 1.1  远程备份方式对比

与SCP的比较：scp无法备份大量数据，而且是全量备份。
而rsync边复制，边统计，边比较，并且是增量备份





#### 1.2  Rsync特性和优点

(1) 可以镜像保存整个目录树和文件系统。
(2) 可以很容易做到保持原来文件的权限、时间、软硬链接等等。
(3) 无须特殊权限即可安装。
(4) 快速：第一次同步时 rsync 复制全部内容，但在下一次只传输修改过的文件。
(5) 压缩传输：rsync 在传输数据的过程中可以实行压缩及解压缩操作，因此可以使用更少的带宽。
(6) 安全：可以使用ssh方式来传输文件。
(7) 支持匿名传输，以方便进行网站镜像。
(8) 选择性保持：符号连接，硬链接，文件属性，权限，时间等。

快速性：
第一次同步时 rsync 会将指定目录下全部内容复制同步，但在下一次只传输修改过的内容。

安全性：
可以使用scp、ssh等方式来传输文件，当然也可以通过直接的socket连接。
选择性保持：符号连接，硬链接，文件属性，权限，时间等。

压缩传输：
rsync 在传输数据的过程中可以实行压缩及解压缩操作，因此可以使用更少的带宽。



#### 1.3  常见备份分类

（1） 完整备份：每次备份都是从备份源将所有的文件或目录备份到目的地。
（2） 差量备份：备份上次完全备份以后有变化的数据（他针对的上次的完全备份，他备份过程中不清除存档属性）。
（3） 增量备份：备份上次备份以后有变化的数据（他才不管是那种类型的备份，有变化的数据就备份，他会清除存档属性）。



#### 1.4  RSYNC原理

1．运行模式和端口：
（1） 采用C/S模式（客户端/服务器模式）[ 实际上是一个点到点的传输，直接使用rsync命令即可完成 ]
（2） rsync监听的端口：873

2．四个名词的解释：
发起端：负责发起rsync同步操作的客户机叫做发起端，通知服务器我要备份你的数据。
备份源：负责响应来自客户机rsync同步操作的服务器叫做备份源，需要备份的服务器。
服务端：运行rsyncd服务，一般来说，需要备份的服务器。
客户端：存放备份数据。

![image-20220415095901216](https://note-1308251438.cos.ap-guangzhou.myqcloud.com/typora/202204150959264.png)



3．数据同步方式：
推push：一台主机负责把数据传送给其他主机，服务器开销很大，比较适合后端服务器少的情况。
拉pull：所有主机定时去找一台主机拉数据，可能就会导致数据缓慢。
推：目的主机配置为rsync服务器，源主机周期性的使用rsync命令把要同步的目录推过去（需要备份的机器是客户端，存储备份的机器是服务端）。
拉：源主机配置为rsync服务器，目的主机周期性的使用rsync命令把要同步的目录拉过来（需要备份的机器是服务端，存储备份的机器是客户端）。
两种方案，rsync都有对应的命令来实现。

rsync命令示例说明push和pull，如图 2-1 所示
![file://c:\users\admini~1\appdata\local\temp\tmpsy2cxr\1.png](https://s2.loli.net/2022/02/14/LetFITgVhlnvcxz.png)
图 2-1 push和pull示意图



#### 2.1  rsync命令选项

通常常用的选项 <font color='red'>–avz</font>

(1) -a：--archive archive mode 权限保存模式，相当于 -rlptgoD 参数，存档，递归，保持属性等。
(2) -r：--recursive 复制所有下面的资料，递归处理。
(3) -p：--perms 保留档案权限，文件原有属性。
(4) -t：--times 保留时间点，文件原有时间。
(5) -g：--group 保留原有属组。                                                                                        
(6) -o：--owner 保留档案所有者(root only)。
(7) -D：--devices 保留device资讯(root only)。     
(8) -l：--links 复制所有的软连接，拷贝连接文件。
(9) -z：--compress 压缩模式，当资料在传送到目的端进行档案压缩。
(10) -P：只是为了把参数简单化，表示传进度。
(11) -v：--verbose 复杂的输出信息。
(12) -u：--update 仅仅进行更新，也就是跳过已经存在的目标位置，并且文件时间要晚于要备份的文件，不覆盖新的文件。
(13) --port=PORT：定义rsyncd(daemon)要运行的port(预设为tcp 873)。
(14) --delete：删除那些目标位置有的文件而备份源没有的文件。
(15) --password-file=FILE ：从 指定密码文件中获取密码。
(16) --bwlimit=KBPS：限制 I/O 带宽。
(17) --exclude=filname：需要过滤的文件。



### 2.rsync工作模式

#### 2.1、本地模式：rsync类似于cp命令

```
注：rsync中/etc 与/etc/ 不同的
/etc 		表示目录及目录下面的内容
/etc/		表示目录下面的内容，不包含目录

[root@exrcise1 opt]# rsync -a /etc /opt
[root@exrcise1 opt]# ll
总用量 12
drwxr-xr-x 77 root root 8192 8月  16 23:42 etc

[root@exrcise1 opt]# rsync -a /etc/ /opt/test
总用量 1076
-rw-r--r--  1 root root       16 1月   4 2022 adjtime
-rw-r--r--  1 root root     1518 6月   7 2013 aliases
-rw-r--r--  1 root root    12288 1月   4 2022 aliases.db
drwxr-xr-x  2 root root      236 1月   4 2022 alternatives
-rw-------  1 root root      541 8月   3 2017 anacrontab
-rw-r--r--  1 root root       55 3月   1 2017 asound.conf
drwxr-x---  3 root root       43 1月   4 2022 audisp
drwxr-x---  3 root root       83 1月   4 2022 audit
drwxr-xr-x  2 root root       22 1月   4 2022 bash_completion.d
-rw-r--r--  1 root root     2870 7月  17 23:18 bashrc
drwxr-xr-x  2 root root        6 8月   5 2017 binfmt.d
-rw-r--r--  1 root root       38 8月  30 2017 centos-release
-rw-r--r--  1 root root       51 8月  30 2017 centos-release-upstream
.........

```





#### 2.2、远程模式：ssh模式

2.2.1、push 推

```
[root@exrcise1 opt]# rsync -avz /etc/hosts  192.168.245.131:/tmp
The authenticity of host '192.168.245.131 (192.168.245.131)' can't be established.
ECDSA key fingerprint is SHA256:ay664UEjR1LZBVZkKjA7oT5JwbbOQTcOIZ+h329xRG8.
ECDSA key fingerprint is MD5:52:cb:f3:78:57:a0:1a:7e:f2:db:a2:ce:b5:e6:8b:8a.
Are you sure you want to continue connecting (yes/no)? yes    
Warning: Permanently added '192.168.245.131' (ECDSA) to the list of known hosts.
root@192.168.245.131's password: 
bash: rsync: 未找到命令									#出现这种情况，主要是因为192.168.245.131上没有安装rsync
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: remote command not found (code 127) at io.c(226) [sender=3.1.2]

[root@exercise2 ~]# yum install -y rsync

[root@exrcise1 opt]# rsync -avz /etc/hosts  192.168.245.131:/tmp
root@192.168.245.131's password: 
sending incremental file list

sent 38 bytes  received 12 bytes  20.00 bytes/sec
total size is 158  speedup is 3.16


[root@exercise2 ~]# ll /tmp
总用量 4
-rw-r--r-- 1 root root 158 6月   7 2013 hosts

```

2.2.2、pull  拉

```
[root@exrcise1 opt]# rsync -avz 192.168.245.131:/etc/hostname  /opt
root@192.168.245.131's password: 
receiving incremental file list
hostname

sent 43 bytes  received 101 bytes  57.60 bytes/sec
total size is 10  speedup is 0.07
[root@exrcise1 opt]# ll
总用量 28
drwxr-xr-x 77 root root 8192 8月  16 23:42 etc
-rw-r--r--  1 root root   10 8月  15 19:47 hostname
drwxr-xr-x 77 root root 8192 8月  16 23:42 test

```

非默认ssh端口同步：

[root@exrcise1 opt]# rsync -avz -e "ssh -p 2222"  /etc/hosts  192.168.245.131:/tmp



如何实现免密传输？

```
[root@home opt]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:s++fdTV6kQ7Lc+btSMf0AMG5MerPTKPkQmyI32ip4hc root@home
The key's randomart image is:
+---[RSA 2048]----+
|           ...   |
|            =.   |
|           ..+   |
|          . ..  .|
|     . oS.   ..+o|
|    E . +oo + =+=|
|     o *.o * *o==|
|  . . = o.o ++*+.|
| ..o.o   oo.o .oo|
+----[SHA256]-----+
[root@home opt]# ssh-copy-id -i ~/.ssh/id_rsa 192.168.245.131
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.245.131's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.245.131'"
and check to make sure that only the key(s) you wanted were added.

```



常见错误：

```
[root@exrcise1 opt]# rsync -avz 192.168.112.131:/etc/hostname /opt
ssh: connect to host 192.168.112.131 port 22: Connection refused      	#或者是 no route to host
rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]
rsync error: unexplained error (code 255) at io.c(226) [Receiver=3.1.2]
```

排查：

1.selinux 或防火墙

2.检查IP是否通畅







#### 2.3、rsync守护进程模式（rsync服务）

服务端步骤：1.检查软件是否安装

​						2.检查配置文件

​						3.根据配置文件，创建用户，文件，目录

​						4.启动服务并测试

客户端步骤：1.检查软件是否安装

​						2.使用rsync命令





##### 1.rsyncd.conf配置文件：

配置文件分为两部分：全局参数、模块参数。
全局参数：对rsync服务器生效，如果模块参数和全局参数冲突，冲突的地方模块参数最终生效。
模块参数：定义需要通过rsync输出的目录定义的参数。

（1） 常见的全局参数：
port          #指定后台程序使用的端口号，默认为873。

uid            #该选项指定当该模块传输文件时守护进程应该具有的uid，配合gid选项使用可以确定哪些可以访问怎么样的文件权限，默认值是" nobody"。

gid            #该选项指定当该模块传输文件时守护进程应该具有的gid。默认值为" nobody"。

max connections        #指定该模块的最大并发连接数量以保护服务器，超过限制的连接请求将被告知随后再试。默认值是0，也就是没有限制。

lock file                  #指定支持max connections参数的锁文件，默认值是/var/run/rsyncd.lock。

motd file         #" motd file"参数用来指定一个消息文件，当客户连接服务器时该文件的内容显示给客户，默认是没有motd文件的。

log file             #" log file"指定rsync的日志文件，而不将日志发送给syslog。

pid file              #指定rsync的pid文件，通常指定为“/var/run/rsyncd.pid”，存放进程ID的文件位置。

read only         #yes为只允许下载，no为可以下载和上传文件到服务器。

auth users       		#该选项指定由空格或逗号分隔的用户名列表，只有这些用户才允许连接该模块。这里的用户和系统用户没有任何关系。如果" auth users"被设置，那么客户端发出对该模块的连接请求以后会被rsync请求challenged进行验证身份这里使用的challenge/response认证协议。用户的名和密码以明文方式存放在" secrets file"选项指定的文件中。默认情况下无需密码就可以连接模块（也就是匿名方式）。

secrets file      		#该选项指定一个包含定义用户名:密码对的文件。只有在" auth users"被定义时，该文件才有作用。文件每行包含一个username:passwd对。一般来说密码最好不要超过8个字符。没有默认的secures file名，注意：该文件的权限一定要是600，否则客户端将不能连接服务器。

hosts allow      	#指定哪些IP的客户允许连接该模块。定义可以是以下形式：
单个IP地址，例如：192.167.0.1，多个IP或网段需要用空格隔开。
整个网段，例如：192.168.0.0/24，也可以书写为192.168.0.0/255.255.255.0
“*”则表示所有，默认是允许所有主机连接。

hosts deny      		#指定不允许连接rsync服务器的机器，可以使用hosts allow的定义方式来进行定义。默认是没有hosts deny定义。

list              		#该选项设定当客户请求可以使用的模块列表时，该模块是否应该被列出。如果设置该选项为false，可以创建隐藏的模块。默认值是true。

timeout   			#通过该选项可以覆盖客户指定的IP超时时间。通过该选项可以确保rsync服务器不会永远等待一个崩溃的客户端。超时单位为秒钟，0表示没有超时定义，这也是默认值。对于匿名rsync服务器来说，一个理想的数字是600。

（2） 常见的模块参数：
主要是定义服务器哪个要被同步输出，其格式必须为“ [ 共享模块名 ]” 形式，这个名字就是在 rsync 客户端看到的名字，其实很像 samba 服务器提供的共享名。而服务器真正同步的数据是通过 path 来指定的。

Comment         #给模块指定一个描述，该描述连同模块名在客户连接得到模块列表时显示给客户。默认没有描述定义。

path                  #指定该模块的供备份的目录树路径，该参数是必须指定的。



##### 2.环境准备

| 主机  | 角色       | IP              |
| ----- | ---------- | --------------- |
| home1 | 备份服务器 | 192.168.245.130 |
| home2 | 备份源     | 192.168.245.131 |





##### 3.用配置文件定义目录输出。

[root@home1 ~]# vim /etc/rsyncd.conf                    #官方配置文件参数少，尽量手动创建。

```
注意： #会出现因注释不兼容的问题而导致推数据时出现报错，配置文件需取消注释或者注释进行换行处理。

uid = rsync                          	#运行进程的身份。
gid = rsync                          	#运行进程的组。
port =873                               #监听端口。
hosts allow =192.168.245.0/24                        
#允许同步客户端的IP地址，可以是网段，或者用*表示所有 192.168.1.0/24或192.168.1.0/255.255.255.0
use chroot = yes                        #是否囚牢，锁定家目录，rsync被黑之后，黑客无法在rsync运行										   的家目录之外创建文件，选项设置为yes。
max connections =200                    #最大连接数。
read only = false                       #是否只读，false关闭
list = false                        	#是否允许客户端查看备份内容， 一般不允许。
#以下两个文件需手动创建
auth users = rsyncuser                  #备份的用户（虚拟用户，不存在系统中）。
secrets file =/etc/rsync.passwd        	#存放用户的密码文件，格式是  用户名：密码   ，同样是创建。
motd file =/etc/rsyncd.motd     	    #客户端登陆之后弹出的消息，需要创建。
#以下三个文件会自动创建
pid file =/var/run/rsyncd.pid           #进程PID，自动生成。
lock file =/var/run/rsync.lock         	#指max connectios参数的锁文件。
log file =/var/log/rsyncd.log          	#日志文件位置。

[wwwroot]                               #共享模块名称。
path =/web-back                         #路径。
comment = used for web-data root    	#描述。
```



##### 4.创建rsync服务用户

```
[root@home1 ~]# useradd rsync -s /sbin/nologin
```





##### 5.创建提示文件和用户密码。

```
#编辑欢迎信息文件。
[root@home1 ~]# echo "Welcome to Backup Server" > /etc/rsyncd.motd	

[root@home1 ~]# vim /etc/rsync.passwd		#创建并编写密码文件。
rsyncuser:123456							#格式为 用户名称：密码。

[root@home1 ~]# chmod 600 /etc/rsync.passwd                 #密码文件权限必须是700或者600，否则的话身份验证会失效。
```





##### 6.创建备份目录并修改权限

```
[root@home1 ~]# mkdir /web-back

[root@home1 ~]# chown rsync:rsync /web-back		#所有者与所属组需对应rsync配置文件的uid与gid
```



##### 7.启动rsync服务

```
[root@home1 ~]# systemctl start rsyncd
```





##### 8.推测试

rsync语法：rsync 选项 用户名@备份源服务器IP::共享模块名 目标目录

```
[root@home2 yum.repos.d]# rsync -avz /etc/hostname  rsyncuser@192.168.245.130::wwwroot
welcome to backup server

Password: 			#输入密码：123456
sending incremental file list
hostname

sent 75 bytes  received 27 bytes  7.03 bytes/sec
total size is 6  speedup is 0.06

```



##### 9.拉测试

```
[root@home2 ~]# rsync -avz   rsyncuser@192.168.245.130::wwwroot /tmp 
welcome to backup server

Password: 
receiving incremental file list
./
hostname

sent 78 bytes  received 192 bytes  77.14 bytes/sec
total size is 6  speedup is 0.02

```



互动：如果服务端改了ssh端口为2222, 此时rsync同步有影响吗？





### 3.rsync应用案例

3.1基础备份案例

目标：

备份网站代码，网站服务配置，脚本

服务器本地保留30天，备份服务器保留180天

备份服务器需要把客户端的IP作为备份的目录名

步骤：

打包备份

网站代码：/var/www/html

配置文件：/etc/httpd/conf

日志：暂时不备份

通过rsync传输备份到备份服务器（与定时任务配合）



![image-20220817202230229](https://note-1308251438.cos.ap-guangzhou.myqcloud.com/typora/202208172022290.png)





实战：

| 角色        |                  |                 |
| ----------- | ---------------- | --------------- |
| rsync服务端 | backup           | 192.168.245.130 |
| rsync客户端 | nfs（装代码）    | 192.168.245.131 |
| rsync客户端 | web1（配置文件） | 192.168.245.131 |








### 5.rsync+sersync实现数据实时同步

一台装sersync、一台装rsync服务
sersync服务器（数据源，源机器）：192.168.1.63
rsync客户端（备份端，目标机器）：192.168.1.64

1. 为什么要用rsync+sersync架构？
   （1） sersync是基于inotify开发的，类似于inotify-tools的工具。
   （2） sersync可以记录下被监听目录中发生变化的（包括增加、删除、修改）具体某一个文件或者某一个目录的名字，然后使用rsync同步的时候，只同步发生变化的文件或者目录。

2. rsync+inotify-tools与rsync+sersync架构的区别？

   （1） rsync+inotify-tools
     1） inotify只能记录下被监听的目录发生了变化（增，删，改）并没有把具体是哪个文件或者哪个目录发生了变化记录下来。
     2） rsync在同步的时候，并不知道具体是哪个文件或目录发生了变化，每次都是对整个目录进行同步，当数据量很大时，整个目录同步非常耗时（rsync要对整个目录遍历查找对比文件），因此效率很低。

​      （2） rsync+sersync
​         1） sersync可以记录被监听目录中发生变化的（增，删，改）具体某个文件或目录的名字。
​         2） rsync在同步时，只同步发生变化的文件或目录（每次发生变化的数据相对整个同步目录数据来说很小，rsync在遍历查找对比文件时，速度很快），因此效率很高。

3. 同步过程：
   （1） 在同步服务器上开启sersync服务，sersync负责监控配置路径中的文件系统事件变化。
   （2） 调用rsync命令把更新的文件同步到目标服务器。
   （3） 需要在主服务器配置sersync，在同步目标服务器配置rsync server（注意：是rsync服务）。

4. 同步过程和原理：
   （1） 用户实时的往sersync服务器上写入更新文件数据。
   （2） 此时需要在同步主服务器上配置sersync服务。
   （3） 在另一台服务器开启rsync守护进程服务，以同步拉取来自sersync服务器上的数据。
   （4） 在另一台服务器开启rsync守护进程服务，使sersync push文件过来。

通过rsync的守护进程服务后可以发现，实际上sersync就是监控本地的数据写入或更新事件，然后，在调用rsync客户端的命令，将写入或更新事件对应的文件通过rsync推送到目标服务器，如图 2-3 所示。
![file://c:\users\admini~1\appdata\local\temp\tmpsy2cxr\3.png](https://s2.loli.net/2022/02/14/q2DFEHYJlr4xVoC.png)
图2-3 同步过程示意图



#### 3.1  下载sersync

1．在google code下载sersync的可执行文件版本，里面有配置文件与可执行文件
wget https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/sersync/sersync2.5.4_64bit_binary_stable_final.tar.gz（有时下载失败，所有要本地留存一份）

2．上传到服务器 /opt目录下。
[root@home2 ~]# cd /opt			#切换工作目录到/opt目录下。
[root@home2 opt]# tar xvf sersync2.5.4_64bit_binary_stable_final.tar.gz		#解压。
[root@home2 opt]# mv GNU-Linux-x86 sersync		#解压后的文件重命名为sersync。
[root@home2 opt]# cd sersync
[root@home2 sersync]# ll
总用量 1776
-rwxr-xr-x 1 root root    2226 4月  15 15:09 confxml.xml					#此为sersync配置文件
-rwxr-xr-x 1 root root 1810128 10月 26 2011 sersync2						#此为sersync主程序文件

3.创建密码文件

参考2.3.6密码处理，

#### 3.2  修改sersync配置文件

[root@home2 opt]# cd sersync		#切换工作目录至sersync目录下。
[root@home2 sersync]# cp confxml.xml confxml.xml.bak		#备份配置文件，便于二次修改

1. 更改优化sersync配置文件：
   [root@home2 sersync]# vim confxml.xml 	   #修改配置文件中的24--28行，如下所示。

   ```
   <sersync>
           <localpath watch="/opt/test">    	#本地同步数据目录。
               <remote ip="192.168.1.64" name="wwwroot"/>   #rsync模块名称
   ```

2. 修改31--34行，认证部分（rsync密码认证）。

   ```jsp
   <rsync>
               <commonParams params="-avz"/>
               <auth start="true" users="rsyncuser" passwordfile="/etc/rsync.passwd"/>
               <userDefinedPort start="false" port="874"/><!-- port=874 -->
               <timeout start="false" time="100"/><!-- timeout=100 -->
               <ssh start="false"/>
   ```

#### 3.3 开启sersync守护进程同步数据

[root@home2 sersync]# /opt/sersync/sersync2  -d -r -o  /opt/sersync/confxml.xml
![file://c:\users\admini~1\appdata\local\temp\tmpsy2cxr\4.png](https://s2.loli.net/2022/02/14/qto3eKA5InrLNhU.png)
图 2-4 开启sersync守护进程

![file://c:\users\admini~1\appdata\local\temp\tmpsy2cxr\5.png](https://s2.loli.net/2022/02/14/UheHWP3lxd1FpqG.png)

#### 3.4 测试

（1） 在63 /opt/test/ 目录 增加、删除、或改目录文件。
（2） 看64 /web-back 目录的变化
[root@home1 web-back]# watch ls -l

5. 设置sersync监控开机自动执行
   [root@home2 sersync]# vi /etc/rc.d/rc.local 	  #编辑rc.local文件，在最后添加一行。(需添加执行权限x)
   /opt/sersync/sersync2 -d -r -o  /opt/sersync/confxml.xml  	＃设置开机自动运行脚本。

6. 添加脚本监控sersync是否正常运行
   [root@home2 ~]# vim /opt/check_sersync.sh  	#编辑脚本，添加以下代码。
   \#!/bin/sh
   sersync="/opt/sersync/sersync2"
   confxml="/opt/sersync/confxml.xml"
   status=$(ps aux |grep 'sersync2'|grep -v 'grep'|wc -l)
   if [ $status -eq 0 ];
   then
   $sersync -d -r -o $confxml &
   else
   exit 0;
   fi
   [root@home2 ~]# chmod +x /opt /check_sersync.sh  	#添加脚本执行权限。
   把这个脚本加到任务计划，定期执行检测。



### 4、实战：liunx系统中文件删除的几种方式



