Linux高效备份:rsync + inotify实时同步

一、rsync 简介

rsync(Remote Sync)是 Linux 系统下的数据镜像备份工具,支持本地复制、远程同步(通过 SSH 或 rsync 协议),是一个快速、安全、高效的增量备份工具。


二、rsync 特性

  • 支持镜像保存整个目录树和文件系统;
  • 保留文件权限、时间、软硬链接等属性;
  • 无须特殊权限即可安装;
  • 增量备份:仅传输修改过的文件,支持压缩传输,节省带宽;
  • 安全:支持 SSH、SCP 等方式加密传输;
  • 支持匿名传输,常用于网站镜像。

三、rsync 的认证协议

rsync 同步前需认证,支持两种协议:

  1. SSH 协议(常用)
  2. rsync 协议 (需启动 rsyncd 服务)

若使用 SSH 认证,无需启动 rsync 服务端守护进程,只需远程主机的用户名和密码即可同步。若不想每次输入密码,可使用 ssh-keygen -t rsa 设置免密登录。

常用命令示例:
bash 复制代码
# 默认使用 SSH 协议(省略 -e ssh)
rsync -avz /SRC root@192.168.100.20:/DEST

# 指定 SSH 端口,默认是22
rsync -avz /SRC -e "ssh -p2222" root@192.168.100.20:/DEST
常用选项说明:
选项 说明
-a, --archive 归档模式,保留所有属性
-v, --verbose 显示详细输出
-q, --quiet 静默模式,不输出信息
-r, --recursive 递归传输目录
-p, --perms 保留权限
-z, --compress 压缩传输
--delete 删除目标端有而源端没有的文件

四、rsync 命令格式与工作模式

三种命令格式:
bash 复制代码
rsync [OPTION]... SRC DEST
rsync [OPTION]... SRC [USER@]HOST:DEST
rsync [OPTION]... [USER@]HOST:SRC DEST
对应三种工作模式:
  1. 本地拷贝(SRC 和 DEST 均无冒号)
  2. 推送到远程 (DEST 包含 user@host:)
  3. 从远程拉取 (SRC 包含 user@host:)

五、rsync + inotify 实时同步

背景:

rsync 虽高效,但不实时。inotify 是 Linux 内核提供的文件系统事件监控机制,可监听文件/目录的创建、修改、删除等事件。

组合优势:
  • inotify 监控文件变化;
  • 触发 rsync 实时同步;
  • 解决 rsync 非实时性的问题。

六、实战配置:rsync + inotify 实时同步

环境说明:
服务器类型 IP地址 应用 操作系统
源服务器 192.168.100.10 rsync + inotify CentOS 7
目标服务器 192.168.100.20 rsync 服务端 CentOS 7

目标:

将源服务器 /root/etc 实时同步到目标服务器的 /tmp 目录。


配置时钟同步,将源服务器当作时钟服务器

源服务器:

shell 复制代码
[root@server ~] vim /etc/chrony.conf

# Serve time even if not synchronized to a time source.local stratum 10

[root@server ~] systemctl restart chronyd
[root@server ~] systemctl enable chronyd
[root@server ~] hwclock -w

目标服务器:

shell 复制代码
[root@YDH tmp] vim /etc/chrony.conf
server 192.168.100.10 iburst

[root@YDH tmp] systemctl restart chronyd
[root@YDH tmp] systemctl enable chronyd
[root@YDH tmp] hwclock -w
[root@YDH tmp] chronyc sources
210 Number of sources = 1

MS Name/IP address         Stratum Poll Reach LastRx Last sample

===============================================================================

^? 192.168.100.10                0   8     0     -     +0ns[   +0ns] +/-    0ns

步骤一:目标服务器配置(接收端)

关闭防火墙和 SELinux

bash 复制代码
[root@YDH ~] systemctl stop firewalld
[root@YDH ~] systemctl disable firewalld
[root@YDH ~] setenforce 0
[root@YDH ~] sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/sysconfig/selinux

安装 rsync

bash 复制代码
yum -y install rsync

配置 /etc/rsyncd.conf

ini 复制代码
log file = /var/log/rsyncd.log
pidfile = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
secrets file = /etc/rsync.pass

[etc_from_client]
path = /tmp/
comment = sync etc from client
uid = root
gid = root
port = 873
ignore errors = yes
use chroot = no
read only = no
list = no
max connections = 200
timeout = 600
auth users = admin
hosts allow = 192.168.100.10
hosts deny = 192.168.1.1

创建密码文件并设置权限

bash 复制代码
[root@YDH tmp] echo 'admin:redhat' > /etc/rsync.pass
[root@YDH tmp] cat /etc/rsync.pass 
admin:redhat
#设置文件权限
[root@YDH tmp] chmod 600 /etc/rsync*
[root@YDH tmp] ll /etc/rsync*
-rw-------. 1 root root 384 Sep 20 16:14 /etc/rsyncd.conf
-rw-------. 1 root root  13 Sep 20 16:15 /etc/rsync.pass

启动 rsync 服务并设置开机自启

bash 复制代码
[root@YDH ~] rsync --daemon --config=/etc/rsyncd.conf
[root@YDH ~] echo 'rsync --daemon --config=/etc/rsyncd.conf' >> /etc/rc.d/rc.local
[root@YDH ~] netstat -tulnp | grep 873
tcp        0      0 0.0.0.0:873            0.0.0.0:*               LISTEN      2043/rsync          
tcp6       0      0 :::873                 :::*                    LISTEN      2043/rsync 

步骤二:源服务器配置(发送端)

关闭防火墙和 SELinux

bash 复制代码
[root@server ~] systemctl stop firewalld
[root@server ~] systemctl disable firewalld
[root@server ~] setenforce 0
[root@server ~] sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/sysconfig/selinux

安装 rsync 和 inotify-tools

bash 复制代码
[root@server ~] yum -y install rsync inotify-tools

创建密码文件

bash 复制代码
[root@server ~] echo 'redhat' > /etc/rsync.pass
[root@server ~] cat /etc/rsync.pass 
redhat
[root@server ~] chmod 600 /etc/rsync.pass

测试同步是否正常

bash 复制代码
[root@server ~] mkdir -p /root/etc/test
mkdir: created directory '/root/etc'
mkdir: created directory '/root/etc/test'

[root@server ~] rsync -avH --port 873 --progress --delete /root/etc/ admin@192.168.100.20::etc_from_client --password-file=/etc/rsync.pass

sending incremental file list
deleting .font-unix/
deleting .esd-0/socket
deleting .esd-0/
deleting .XIM-unix/
deleting .X11-unix/X1024
deleting .X11-unix/
deleting .Test-unix/
deleting .ICE-unix/1486
deleting .ICE-unix/
deleting .viminfo
deleting .X1024-lock
./
test/

sent 77 bytes  received 191 bytes  536.00 bytes/sec
total size is 0  speedup is 0.00
#运行完成后,在目标服务器上查看,在/tmp目录下有test目录,说明数据同步成功
[root@YDH ~] cd /tmp/
[root@YDH tmp] ls
test

步骤三:配置实时同步脚本

安装inotify-tools工具,实时触发rsync进行同步

shell 复制代码
#查看服务器内核是否支持inotify
[root@server ~] ll /proc/sys/fs/inotify
total 0
-rw-r--r--. 1 root root 0 Sep 20 16:54 max_queued_events
-rw-r--r--. 1 root root 0 Sep 20 16:54 max_user_instances
-rw-r--r--. 1 root root 0 Sep 20  2022 max_user_watches
#如果有这三个max开头的文件则表示服务器内核支持inotify

#安装inotify-tools
[root@server ~] yum -y install make gcc gcc-c++

[root@server ~] yum -y install inotify-tools

#写同步脚本,此步乃最最重要的一步,请慎之又慎。让脚本自动去检测我们制定的目录下 \
#文件发生的变化,然后再执行rsync的命令把它同步到我们的服务器端去

[root@server ~] mkdir /yangduhan
[root@server ~] touch /yangduhan/inotify.sh
[root@server ~] chmod +x /yangduhan/inotify.sh

创建监控脚本 /yangduhan/inotify.sh

bash 复制代码
[root@server ~] vim /yangduhan/inottify.sh

#!/bin/bash	
host=192.168.100.20		# 目标服务器的ip(备份服务器)
src=/root/etc			# 在源服务器上所要监控的备份目录(此处可以自定义,但是要保证存在)
des=etc_from_client		# 自定义的模块名,需要与目标服务器上定义的同步名称一致
password=/etc/rsync.pass	# 执行数据同步的密码文件
user=admin				# 执行数据同步的用户名
inotifywait=/usr/bin/inotifywait

$inotifywait -mrq --timefmt '%Y%m%d %H:%M' --format '%T %w%f%e' \
  -e modify,delete,create,attrib $src | while read files; do
    rsync -avzP --delete --timeout=100 --password-file=$password $src $user@$host::$des
    echo "${files} was rsynced" >> /tmp/rsync.log 2>&1
done

赋予执行权限并后台运行

bash 复制代码
[root@server ~] chmod +x /yangduhan/inotify.sh
[root@server ~] nohup /bin/bash /yangduhan/inotify.sh &
[1] 32503
 nohup: ignoring input and appending output to 'nohup.out'

[root@server ~] ps -ef | grep inotify
root       32503    2458  0 17:05 pts/1    00:00:00 bash /yangduhan/inotify.sh
root       32504   32503  0 17:05 pts/1    00:00:00 /usr/bin/inotifywait -mrq --timefmt %Y%m%d %H:%M --format %T %w%f%e -e modify,delete,create,attrib /root/etc
root       32505   32503  0 17:05 pts/1    00:00:00 bash /yangduhan/inotify.sh
root       32510    2458  0 17:05 pts/1    00:00:00 grep --color=auto inotify

设置开机自启

bash 复制代码
echo 'nohup /bin/bash /yangduhan/inotify.sh &' >> /etc/rc.d/rc.local

步骤四:验证实时同步

在源服务器创建文件:

bash 复制代码
[root@localhost ~] touch /root/etc/ydh123

查看日志:

sh 复制代码
[root@server ~] tail -f /tmp/rsync.log
20220920 17:06 /root/etc/ydh123CREATE was rsynced
20220920 17:06 /root/etc/ydh123ATTRIB was rsynced
#从日志上可以看到,我们生成了一个test文件,并且添加了内容到其里面

在目标服务器检查:

sh 复制代码
ls /tmp/etc/

源服务器中,设置脚本开机启动:

shell 复制代码
[root@server ~] chmod +x /etc/rc.d/rc.local 
[root@server ~] ll /etc/rc.d/rc.local 
-rwxr-xr-x. 1 root root 474 Mar 24  2020 /etc/rc.d/rc.local
[root@server ~] echo 'nohup /bin/bash /yangduhan/inotify.sh &' >> /etc/rc.d/rc.local
[root@server ~] tail /etc/rc.d/rc.local 
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local

nohup /bin/bash /yangduhan/inotify.sh &

#到目标服务器上去查看是否把新生成的文件自动传上去了:
[root@YDH tmp] ls
etc  test
[root@YDH tmp] cd etc/
[root@YDH etc] ls
yangduhan123  test
[root@YDH etc] pwd
/tmp/etc

#由此可见,已将源服务器的/root/etc目录整个同步到了目标服务器,且新增的test文件也自动同步了
相关推荐
无忧.芙桃6 小时前
Linux系统编程(四):用户与权限管理
linux·运维·服务器
最强小杰6 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
戊本菌9 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
aningx9 小时前
Arch 系用 greetd 实现开机自动进 Plasma Wayland,注销自动回桌面
linux
张小姐的猫10 小时前
【基于 WebSocket 的多用户网页五子棋】—— 整合封装服务器模块设计实现2️⃣
服务器·websocket·网络协议
江无行者10 小时前
Linux 服务器 top 命令详解
linux
HMS工业网络10 小时前
工业远程访问的五项安全部署原则
运维·服务器·安全
嵌入式 Linux手记12 小时前
一块内存,三种解释:union 的真实用法
linux·c语言·驱动开发·嵌入式
星恒随风13 小时前
MySQL 从零入门(九):事务管理详解——ACID、COMMIT、ROLLBACK、SAVEPOINT 与四种隔离级别
linux·服务器·数据库·笔记·mysql
草莓熊Lotso13 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构