🌀 Rsync 学习

备份简述

什么是备份?备份的方式有哪些?

备份指的是将文件系统或者数据库中的数据进行复制,一旦发生错误或者灾难时,能及时方便地恢复系统的有效数据且正常运作。 一旦发生错误或者灾难时,能及时方便地恢复系统的有效数据且正常运作

  • 完全备份(Full backup):指把硬盘或数据库内的所有文件、文件夹或数据作一次性的复制
  • 增量备份(incremental backup):指对上一次全部备份或增量备份后更新的数据进行备份
  • 差异备份(Differential backup) :指完整备份后变更的文件的备份
  • 选择性备份(Selective backup):指对系统的一部分进行备份
  • 冷备份(Cold backup):指系统处于停机或维护状态下的备份。 备份的数据与系统中此时段的数据完全一致
  • 热备份(Hot backup): 指系统处于正常运转状态下的备份。 由于系统中的数据随时在更新,备份的数据相对于系统的真实数据有一定的滞后
  • 异地备份(Remote backup):指在另外一个地理位置备份数据,避免因为火灾、自然灾害、盗窃等造成数据丢失与服务中断

Rsync简述

在生产环境中,数据量是较大的,我们不建议采用 tar\cp 压缩复制,然后再进行 scp\sftp 远程复制传输;首先, tar 或者 cp 会消耗大量的时间且占用系统的性能。 通过 scp 或者 sftp 传输还会占用大量的网络带宽,这在实际的生产环境下是不被允许的。其次,手动命令操作也比较繁琐,即使搭配计划任务,时间也不好掌握,所以这写方法是不太适用于生产环境的

所以我们需要一种数据备份,满足以下需求:

  1. 通过网络传输
  2. 实时的数据文件同步
  3. 对系统资源占用少,且效率较高

rsync 似乎满足了上述需求。 它使用 GNU 开源许可协议, 是一个快速增量备份的工具,您可以访问官方网站获取更多信息 RPM

rsync 本身是一个增量备份工具,不具备实时数据同步,需要其他工具,此外同步也是单向的,如果您要实现双向同步,需要配合其他工具

基本原理特点

rsync 是如何实现高效的单向数据同步备份的?

rsync 的核心就是它的 Checksum 算法 , 有关更多信息,您可以转到 rsync 的工作原理rsync 算法

rsync 的特点有:

  • 能以递归的形式更新整个目录
  • 能有选择的保留文件同步属性,比如硬链接、软链接、所有者、所属组、对应权限、修改时间等,可以保留其中的一部分属性
  • 支持两种协议进行传输,一个是 ssh 协议,一个是 rsync 协议

基础场景1-基于 SSH 协议

rsync 在进行数据同步之前需要先进行用户身份验证, 有两种协议方式进行身份验证:ssh 协议与 rsync协议( rsync 协议的默认端口为873)

  • SSH 协议验证登录方式:使用 SSH 协议作为基础进行用户身份认证(也就是拿 Linux 本身的系统用户和密码做验证),然后进行数据同步
  • Rsync 协议验证登录方式:使用 Rsync 协议进行用户身份认证( Linux 本身的系统用户,类似于 vsftpd虚拟用户),然后进行数据同步

本次实验我们使用 rocky Linux8.10 版本,自带 rsync 工具

[root@master01 ~]# rsync --version 
rsync  version 3.1.3  protocol version 31
Copyright (C) 1996-2018 by Andrew Tridgell, Wayne Davison, and others.
Web site: http://rsync.samba.org/
Capabilities:
    64-bit files, 64-bit inums, 64-bit timestamps, 64-bit long ints,
    socketpairs, hardlinks, symlinks, IPv6, batchfiles, inplace,
    append, ACLs, xattrs, iconv, symtimes, prealloc

rsync comes with ABSOLUTELY NO WARRANTY.  This is free software, and you
are welcome to redistribute it under certain conditions.  See the GNU
General Public Licence for details.
基本格式:rsync  [选项]  原始位置  目标位置
常用的选项:
-a  :归档模式,递归且保留文件对象的属性,等同于-rlptgoD(没有-H、-A、-X)
-v  :显示同步过程的详细信息
-z  :在传输文件时进行压缩
-H  :保留硬链接文件
-A  :保留ACL权限
-X  :保留chattr权限
-r  :递归模式,包含目录以及子目录中所有的文件
-l  :对于符号链接文件仍然保留
-p  :保留文件属性的权限
-t  :保留文件属性的时间
-g  :保留文件属性的所属组(仅限超级用户使用)
-o  :保留文件属性的所有者(仅限超级用户使用)
-D  :保留设备文件以及其他特殊文件

我们这里准备了2台机器做传输测试:Master01 (Server) Worker01(Client)

Push 测试

[root@master01 ~]# cat test.txt 
I'm Client
[root@master01 ~]# echo "I'm Server" > test.txt 
[root@master01 ~]# cat test.txt 
I'm Server
[root@master01 ~]# rsync -avz test.txt root@worker01:/root
sending incremental file list
test.txt

sent 102 bytes  received 41 bytes  286.00 bytes/sec
total size is 11  speedup is 0.08
[root@master01 ~]# ssh root@worker01 cat /root/test.txt
I'm Server
[root@master01 ~]# 

Pull 测试

[root@master01 ~]# rsync -avz root@worker01:/root/test.txt /root
The authenticity of host 'worker01 (192.168.2.212)' can't be established.
ECDSA key fingerprint is SHA256:whzXiU+Lw+HKgTz1So/lCbsBZ/w0BleHiUjiEi5BOgI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'worker01' (ECDSA) to the list of known hosts.
receiving incremental file list
test.txt

sent 49 bytes  received 101 bytes  100.00 bytes/sec
total size is 11  speedup is 0.07
[root@master01 ~]# ls
test.txt
[root@master01 ~]# cat test.txt 
I'm Client
[root@master01 ~]# 

基础场景2-基于Rsync协议

在 Rocky Linux 8中,需要手动创建 /etc/rsyncd.conf 这个文件。在系统中创建 rsync 配置文件

该文件的部分参数以及值如下,这里 有更多的参数说明

  • address = 192.168.2.211
  • rsync 默认监听的 IP 地址 port = 873
  • rsync 默认监听的端口 pid file = /var/run/rsyncd.pid 进程pid的文件位置
  • log file = /var/log/rsyncd.log 日志的文件位置
  • [share] 共享名称
  • comment = rsync 备注或者描述信息
  • path = /rsync/ 所在的系统路径位置
  • read only = no yes表示只读,no表示可读可写
  • dont compress = *.gz *.gz2 *.zip 哪些文件类型不对它进行压缩
  • auth users = rsync 启用虚拟用户,定义个虚拟用户叫什么。 需要自行创建
  • secrets file = /etc/rsyncd_users.db 用来指定虚拟用户的密码文件位置,必须以 .db 结尾。 文件的内容格式是”用户名:密码”,一行一个

写入一些文件内容到 /etc/rsyncd.conf,且将用户名与密码写入到 /etc/rsyncd_users.db 中,密码文件的权限必须是 600

[root@master01 ~]# vim /etc/rsyncd_users.db
[root@master01 ~]# chmod 600 /etc/rsyncd_users.db
[root@master01 ~]# cat /etc/rsyncd.conf
address = 192.168.2.211
port = 873
pid file = /var/run/rsyncd.pid
log file = /var/log/rsyncd.log

[share]
comment = rsync
path = /data/rsync
read only = no
dont compress = *.gz *.bz2 *.zip
auth users = rsync
secrets file = /etc/rsyncd_users.db

启动rsync服务需要安装 rsync-daemon dnf -y install rsync-daemon安装完成后启动服务:systemctl enable --now rsyncd.service

[root@master01 ~]# dnf -y install rsync-daemon
Last metadata expiration check: 0:36:01 ago on Wed 20 Aug 2025 10:34:27 PM CST.
Dependencies resolved.
======================================================================================================================================
 Package                           Architecture                Version                              Repository                   Size
======================================================================================================================================
Installing:
 rsync-daemon                      noarch                      3.1.3-23.el8_10                      baseos                       44 k
Upgrading:
 rsync                             x86_64                      3.1.3-23.el8_10                      baseos                      411 k

Transaction Summary
======================================================================================================================================
Install  1 Package
Upgrade  1 Package

Total download size: 455 k
Downloading Packages:
(1/2): rsync-3.1.3-23.el8_10.x86_64.rpm                                                               2.7 MB/s | 411 kB     00:00  
(2/2): rsync-daemon-3.1.3-23.el8_10.noarch.rpm                                                        270 kB/s |  44 kB     00:00  
--------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                 2.7 MB/s | 455 kB     00:00   
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                              1/1 
  Upgrading        : rsync-3.1.3-23.el8_10.x86_64                                                                                 1/3 
  Installing       : rsync-daemon-3.1.3-23.el8_10.noarch                                                                          2/3 
warning: /etc/rsyncd.conf created as /etc/rsyncd.conf.rpmnew

  Running scriptlet: rsync-daemon-3.1.3-23.el8_10.noarch                                                                          2/3 
  Cleanup          : rsync-3.1.3-19.el8_7.1.x86_64                                                                                3/3 
  Running scriptlet: rsync-3.1.3-19.el8_7.1.x86_64                                                                                3/3 
  Verifying        : rsync-daemon-3.1.3-23.el8_10.noarch                                                                          1/3 
  Verifying        : rsync-3.1.3-23.el8_10.x86_64                                                                                 2/3 
  Verifying        : rsync-3.1.3-19.el8_7.1.x86_64                                                                                3/3 

Upgraded:
  rsync-3.1.3-23.el8_10.x86_64                                                                                  
Installed:
  rsync-daemon-3.1.3-23.el8_10.noarch                                                                           

Complete!

[root@master01 ~]# systemctl enable --now rsyncd.service
Created symlink /etc/systemd/system/multi-user.target.wants/rsyncd.service → /usr/lib/systemd/system/rsyncd.service.
[root@master01 ~]# systemctl status rsyncd.service
● rsyncd.service - fast remote file copy program daemon
   Loaded: loaded (/usr/lib/systemd/system/rsyncd.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2025-08-20 23:10:51 CST; 3min 20s ago
 Main PID: 10460 (rsync)
    Tasks: 1 (limit: 102148)
   Memory: 288.0K
   CGroup: /system.slice/rsyncd.service
           └─10460 /usr/bin/rsync --daemon --no-detach

Aug 20 23:10:51 master01 systemd[1]: Started fast remote file copy program daemon.

一切准备好之后,我们在 worker01 节点测试下载、上传文件:

# 服务端创建测试文件
[root@master01 ~]# mkdir -p  /data/rsync/
[root@master01 ~]# touch /data/rsync/rsynctest.txt
[root@master01 ~]# ll /data/rsync/rsynctest.txt 
-rw-r--r-- 1 root root 0 Aug 20 23:19 /data/rsync/rsynctest.txt

Pull 测试

[root@worker01 ~]# rsync -avz rsync@master01::share /root
Password: 
receiving incremental file list

sent 20 bytes  received 68 bytes  35.20 bytes/sec
total size is 0  speedup is 0.00
[root@worker01 ~]# ll 
total 4
-rw-r--r-- 1 root root  0 Aug 20 23:19 rsynctest.txt
-rw-r--r-- 1 root root 11 Aug 20 22:55 test.txt

也可以这样写:rsync://rsync@master01/share

! 上传文件操作:配置文件必须设置关闭仅读 read only = no

[root@worker01 ~]# rsync -avz /root/123.txt rsync://rsync@master01/share
Password: 
sending incremental file list
123.txt
rsync: mkstemp "/.123.txt.7BJXy1" (in share) failed: Permission denied (13)

sent 85 bytes  received 115 bytes  57.14 bytes/sec
total size is 0  speedup is 0.00
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1189) [sender=3.1.3]

我们发现上传报错了,提示没有权限,怎么回事呢?我们这里的虚拟用户为 rsync ,它默认映射为 nobody 这个系统用户, 当然您可以更改为其他的系统用户。 换句话说就是,nobody 对 /data/rsync/ 这个目录没有 w 权限。 当然,我们可以使用 [root@master01 ~]# setfacl -m u:nobody:rwx /data/rsync/,再次尝试,成功

  1. 为什么用 nobody 用户?(因为 rsync 守护进程默认用这个低权限用户运行,安全)
  2. 用 chmod 能不能达到同样效果?(能但不够好,chmod 会影响所有其他用户,而 setfacl 只针对 nobody)
  3. 这个命令会不会有安全隐患?(需要说明 rwx 对目录的含义是可进入、可创建文件,正是 rsync 需要的)
[root@worker01 ~]# rsync -avz /root/123.txt rsync://rsync@master01/share
Password: 
sending incremental file list
123.txt

sent 85 bytes  received 35 bytes  48.00 bytes/sec
total size is 0  speedup is 0.00

Rsync+inotify-tools工具,实现单向实时同步

搭配inotify-tools这个程序工具,可以实现单向的实时同步。 既然是实时的数据同步,前提条件是需要免密验证登录

不管是rsync协议,还是SSH协议,两者都能实现免密验证登录。SSH 免密方式,比较简单,就不单独演示了

Rsync 协议免密验证登录

在客户端,rsync 服务为系统准备了一个环境变量—— RSYNC_PASSWORD ,默认是空值,如下所示:

[root@worker01 ~]# echo "$RSYNC_PASSWORD"

[root@worker01 ~]# 

如果要实现免密验证登录,只需要给这个变量赋值就可以了。 所赋的值就是之前给虚拟用户 rsync 设置的密码。 同时将这个变量申明为全局变量

[root@worker01 ~]# export RSYNC_PASSWORD=123.com
[root@worker01 ~]# rsync -avz rsync@master01::share /root
receiving incremental file list
./
123.txt
rsynctest.txt

sent 65 bytes  received 178 bytes  486.00 bytes/sec
total size is 0  speedup is 0.00
[root@worker01 ~]# ls
123.txt  rsynctest.txt

可以将这个变量写入到 /etc/profile 当中,让其永久生效

编译安装 inotify-tools

提前安装依赖包 dnf -y install autoconf automake libtool gcc-c++ make

[root@master01 ~]# dnf -y install autoconf automake libtool gcc-c++ make
Last metadata expiration check: 0:48:45 ago on Mon 25 Aug 2025 10:09:16 AM CST.
Dependencies resolved.
==========================================================================================================================
 Package                         Architecture         Version                               Repository               Size
==========================================================================================================================
Installing:
 autoconf                        noarch               2.69-29.el8_10.1                      appstream               710 k
 automake                        noarch               1.16.1-8.el8                          appstream               713 k
 gcc-c++                         x86_64               8.5.0-26.el8_10                       appstream                12 M
 libtool                         x86_64               2.4.6-25.el8                          appstream               708 k
 make                            x86_64               1:4.2.1-11.el8                        baseos                  497 k
Upgrading:
 libgcc                          x86_64               8.5.0-26.el8_10                       baseos                   81 k
 libgomp                         x86_64               8.5.0-26.el8_10                       baseos                  208 k
 libstdc++                       x86_64               8.5.0-26.el8_10                       baseos                  472 k
Installing dependencies:
 cpp                             x86_64               8.5.0-26.el8_10                       appstream                10 M
 gcc                             x86_64               8.5.0-26.el8_10                       appstream                23 M
 glibc-devel                     x86_64               2.28-251.el8_10.2                     baseos                   86 k
 glibc-headers                   x86_64               2.28-251.el8_10.2                     baseos                  491 k
 isl                             x86_64               0.16.1-6.el8                          appstream               834 k
 kernel-headers                  x86_64               4.18.0-553.69.1.el8_10                baseos                   12 M
 libmpc                          x86_64               1.1.0-9.1.el8                         appstream                60 k
 libstdc++-devel                 x86_64               8.5.0-26.el8_10                       appstream               2.1 M
 libxcrypt-devel                 x86_64               4.1.1-6.el8                           baseos                   24 k
 m4                              x86_64               1.4.18-7.el8                          baseos                  221 k
 perl-Thread-Queue               noarch               3.13-1.el8                            appstream                23 k

Transaction Summary
==========================================================================================================================
Install  16 Packages
Upgrade   3 Packages

下载解压安装包:

[root@master01 ~]# wget https://github.com/inotify-tools/inotify-tools/archive/refs/tags/4.23.9.0.tar.gz
--2025-08-25 11:21:35--  https://github.com/inotify-tools/inotify-tools/archive/refs/tags/4.23.9.0.tar.gz
Resolving github.com (github.com)... 20.205.243.166
Connecting to github.com (github.com)|20.205.243.166|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://codeload.github.com/inotify-tools/inotify-tools/tar.gz/refs/tags/4.23.9.0 [following]
--2025-08-25 11:21:36--  https://codeload.github.com/inotify-tools/inotify-tools/tar.gz/refs/tags/4.23.9.0
Resolving codeload.github.com (codeload.github.com)... 20.205.243.165
Connecting to codeload.github.com (codeload.github.com)|20.205.243.165|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 93281 (91K) [application/x-gzip]
Saving to: ‘4.23.9.0.tar.gz’

4.23.9.0.tar.gz                100%[==================================================>]  91.09K   244KB/s    in 0.4s  

2025-08-25 11:21:37 (244 KB/s) - ‘4.23.9.0.tar.gz’ saved [93281/93281]

[root@master01 ~]# tar -zvxf 4.23.9.0.tar.gz -C /usr/local/src/

执行编译操作:

[root@master01 ~]# cd /usr/local/src/inotify-tools-4.23.9.0/
[root@master01 inotify-tools-4.23.9.0]# ./autogen.sh  && ./configure --prefix=/usr/local/inotify-tools &&  make &&  make install
libtoolize: putting auxiliary files in AC_CONFIG_AUX_DIR, 'config'.
libtoolize: copying file 'config/ltmain.sh'
libtoolize: putting macros in AC_CONFIG_MACRO_DIRS, 'm4'.
libtoolize: copying file 'm4/libtool.m4'
...................................
省略
[root@master01 inotify-tools-4.23.9.0]# ls /usr/local/inotify-tools/bin/
inotifywait  inotifywatch

添加环境变量

# 追加到文件最后即可
vim /etc/profile
PATH=$PATH:/usr/local/inotify-tools/bin/
[root@master01 inotify-tools-4.23.9.0]# source /etc/profile
[root@master01 inotify-tools-4.23.9.0]# inotifywa
inotifywait   inotifywatch 

内核参数调整

编译安装完成后,在 /proc/sys/fs/inotify/目录下有三个参数文件,我们可以根据生产环境进行适当调整参数值

  • max_queued_events – 最多监控队列大小,默认16384
  • max_user_instances – 最多监控实例数,默认128
  • max_user_watches – 每个实例最多监控的文件数,默认8192

写入一些参数与值到 /etc/sysctl.conf 当中,如下。 然后使用 sysctl -p 让文件它们生效

fs.inotify.max_queued_events = 16384
fs.inotify.max_user_instances = 1024
fs.inotify.max_user_watches = 1048576

相关命令介绍

inotify-tools工具有两个命令,分别是:

  • inotifywait – 用于持续监控,实时输出结果
  • inotifywatch – 用于短期监控,任务完成后输出结果

inotifywait 主要参数:

  • -m 表示持续监控
  • -r 递归监控
  • -q 简化输出信息
  • -e 指定监控数据的事件类型,多个事件类型用英文状态的逗号隔开

常用的事件类型:

access文件或目录的内容进行访问
modify文件或目录的内容被写入
attrib文件或目录的属性被修改
close_write文件或目录在可写模式下打开后关闭
close_nowrite文件或目录在以只读模式打开后关闭
close无论读/写模式,文件或目录关闭
open文件或者目录被打开
moved_to有文件或目录移动到监控的目录中
moved_from有文件或目录从监控的目录中移出
move有文件或者目录,被移动到监控目录或者从监控目录中移出
move_self已移动受监视的文件或目录
create被监控的目录内有创建的文件或目录
delete被监控的目录内有文件或目录被删除
delete_self文件或目录已经被删除
unmount包含已卸载文件或目录的文件系统

inotifywait 测试:

[root@master01 rsync]# touch 1.txt
# 复制一个窗口,监控信息
[root@master01 inotify-tools-4.23.9.0]# inotifywait  -mrq  -e  create,delete /data/rsync/
/data/rsync/ CREATE 1.txt

notifywait 和 rsync 的结合使用

我们在 Rocky Linux 8 服务器上操作,使用 SSH 协议进行演示。提前做好免密登录

我们在 Server 节点编写一个脚本,在后台运行这个脚本

#!/bin/bash
a="/usr/local/inotify-tools/bin/inotifywait -mrq -e modify,move,create,delete /data/rsync/"
b="/usr/bin/rsync -avz /data/rsync/* root@worker01:/root/"
$a | while read directory event file
    do
        $b &>> /tmp/rsync.log
    done

我们在服务端启动脚本

[root@master01 ~]# cat rsync.sh 
#!/bin/bash
a="/usr/local/inotify-tools/bin/inotifywait -mrq -e modify,move,create,delete /data/rsync/"
b="/usr/bin/rsync -avz /data/rsync/* root@192.168.2.212:/root/"
$a | while read directory event file
    do
        $b &>> /tmp/rsync.log
    done
[root@master01 ~]# bash rsync.sh 

# 在服务端新增文件
[root@master01 rsync]# ls
1.txt  2.txt  3.txt
[root@master01 rsync]# touch 4.txt
[root@master01 rsync]# cat /tmp/rsync.log

sending incremental file list
1.txt
2.txt
3.txt
4.txt

sent 251 bytes  received 92 bytes  228.67 bytes/sec
total size is 0  speedup is 0.00

# Worker节点收到传输过来的文件

[root@worker01 ~]# ls
1.txt  2.txt  3.txt  4.txt
[root@worker01 ~]# 

总结

上述实验,只是一个简单示例,你可以根据自己的需求,优化脚本内容并设置为自启动服务,实现数据变动监控并自动触发脚本备份传输

参考文献

【1】rsync 官网

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇