目 录CONTENT

文章目录

rsync远程同步

简中仙
2024-03-01 / 0 评论 / 0 点赞 / 155 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于2024-03-01,若内容或图片失效,请留言反馈。 本文如有错误或者侵权的地方,欢迎您批评指正!

一、配置rsync源服务器

rsync(Remote Sync,远程同步)是一个开源的快速备份工具,可以在不同主机之间镜像同步整个目录树,支持增量备份,保持链接和权限,且采用优化的同步算法,传输前执行压缩,因此非常适用于异地备份、镜像服务器等应用。

rsync的官方站点是https://rsync.samba.org/ ,目前最新版本是3.3.0,由Wayne Davison进行维护。作为一种最常用的文件备份工具,rsync往往是Linux和UNIX系统默认安装的基本组件之一。本章以CentOS7.9系统中的rsync-3.1.2-12为例。

# rpm -q rsync
rsync-3.1.2-12.el7_9.x86_64

1、建立配置文件

# vim /etc/rsyncd.conf
# 运行进程的用户
uid = nobody
# 运行进程的组
gid = nobody
# 禁锢在源目录
use chroot = yes
# 模块的最大并发连接数量
max connections = 10
# 监听地址
address = 192.168.1.10
# 监听端口
port 873
# 日志文件位置
log file = /var/log/rsyncd.log
# 存放进程ID的文件位置
pid file = /var/run/rsyncd.pid
# 允许访问的客户机地址
hosts allow = 192.168.1.0/24
# 共享模块名称
[wwwroot]
		uid = root
        gid = root
        # 源目录的实际位置
        path = /var/www/html
        comment = Document Root of www.admin.com
        # 忽略一些无关的IO错误
        # ignore errors
        # 是否为只读,当inotify所在的发起端要上传数据时设置为no
        read only = yes
        # 同步时不再压缩的文件类型
        dont compress = *.gz *.bz2 *.ygz *.zip *.rar *.z
        # 授权账户
        auth users = backuper
        # 存放账户信息的数据文件
        secrets file = /etc/rsyncd_users.db

基于安全性考虑,对于rsync的同步源最好仅允许以只读方式做同步。另外,同步可以采用匿名的方式,只要将其中的"auth users"和"secrets file"配置记录去掉就可以了。

2、为备份账户创建数据文件

# vim /etc/rsyncd_users.db
backuper:pwd123              # 无须建立同名系统用户
# chmod 600 /etc/rsyncd_users.db 
# mkdir -p /var/www/html

3、启动rsync服务程序,运行参数为"--daemon"

# rsync --daemon
# netstat -anpt | grep rsync
tcp        0      0 192.168.1.10:873        0.0.0.0:*               LISTEN      23296/rsync  
# kill $(cat /var/run/rsyncd.pid)              # 杀死进程
# rsync --daemon --config=/etc/rsyncd.conf              # 重启

二、使用rsync备份工具

1、rsync命令的基本用法

# rsync /etc/fstab /opt/
# rsync -rl /etc/fstab /boot/grub /opt/              # 将文件/etc/fstab、目录/boot/grub同步备份到/opt目录下
常用备份选项说明常用备份选项说明
-r递归模式,包含目录及子目录中的所有文件-I对于符号链接文件仍然复制为符号链接文件
-v显示同步过程的详细信息-a归档模式,保留文件的权限、属性等信息
-z在传输文件时进行压缩-p保留文件的权限标记
-t保留文件的时间标记-g保留文件的属组标记(仅超级用户使用)
-o保留文件的属主标记(仅超级用户使用)-H保留硬连接文件
-A保留ACL属性信息-D保留设备文件及其他特殊文件
--delete删除目标位置有而原始位置没有的文件--checksum根据校验和(而不是文件大小、修改时间)来决定是否跳过文件

2、配置源的表示方法

将访问rsync同步源,将指定的资源下载到本地/root目录下进行备份

# rsync -avz backuper@192.168.1.10::wwwroot /root
Password: 
receiving incremental file list
./

sent 64 bytes  received 97 bytes  10.39 bytes/sec
total size is 0  speedup is 0.00

# rsync -avz rsync://backuper@192.168.1.10/wwwroot /root
Password: 
receiving incremental file list

sent 61 bytes  received 94 bytes  28.18 bytes/sec
total size is 0  speedup is 0.00

2、rsync备份操作

1、将访问源服务器中的wwwroot共享模块,并下载到本地的/myweb目录下

# yum -y install httpd
# mkdir /myweb
# rsync -avzH --delete backuper@192.168.1.10::wwwroot /myweb/
Password: 
receiving incremental file list
./
index.html
index.php

sent 102 bytes  received 205 bytes  47.23 bytes/sec
total size is 0  speedup is 0.00

2、每天晚上22: 30对服务器的网站目录做一次同步

# vim /etc/server.pass              # 创建密码文件,保存backuper用户的密码
pwd123
# chmod 600 /etc/server.pass
# crontab -e
30 22 * * * /usr/bin/rsync -az --delete --password-file=/etc/server.pass backuper@192.168.1.10::wwwroot /myweb
# systemctl restart crond
# systemctl enable crond

三、配置inotify+rsync架构

Linux内核从2.6.13版本开始提供了inotify通知接口,用来监控文件系统的各种变化情况,如文件存取、删除、移动、修改等。利用这一机制,可以非常方便地实现文件异动告警,增量备份,并针对目录或文件的变化及时作出响应。

将inotify机制与rsync工具相结合,可以实现触发式备份(实时同步)——只要原始位置的文档发生变化,则立即启动增量备份操作,否则处于静默等待状态。这样,就避免了按固定周期备份时存在的延迟性、周期过密等问题。

1、调整inotify内核参数

# vim /etc/sysctl.conf
# 监控事件队列
fs.inotify.max_queued_events = 16384
# 实例数
fs.inotify.max_user_instances = 1024
# 监控数
fs.inotify.max_user_watches = 1048576
# sysctl -p

2、安装 inotify-tools

# wget --no-check-certificate https://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
# tar zxf inotify-tools-3.14.tar.gz -C /usr/src/
# cd /usr/src/inotify-tools-3.14/
# ./configure && make && make install

选项"-e"用来指定要监控哪些事件,选项"-m"表示持续监控,选项"-r"表示递归整个目录,选项"-q"简化输出信息

# inotifywait -mrq -e modify,create,attrib,move,delete /var/www/html/               

inotifywait可监控modify(修改)、create(创建)、move(移动),delete(删除),attrib(属性更改)等各种事件,一有变动立即输出结果;inotifywatch可用来收集文件系统变动情况,并在运行结束后输出汇总的变化情况。

3、编写触发式同步脚本

用来检测本机192.168.1.20/var/www/html目录的变动情况,一旦有更新触发rsync同步操作,上传备份至服务器192.168.1.10的/var/www/html目录下

# vim /etc/server.pass
pwd123
# chmod 600 /etc/server.pass 
# vim /opt/inotify_rsync.sh
#!/bin/bash
INOTIFY_CMD="inotifywait -mrq -e modify,create,attrib,move,delete /var/www/html/"
RSYNC_CMD="rsync -azh --delete --password-file=/etc/server.pass /var/www/html backuper@192.168.1.10::wwwroot"
$INOTIFY_CMD | while read DIRECTORY EVENT FILE
do
        $RSYNC_CMD
done
# chmod +x /opt/inotify_rsync.sh 
# echo '/opt/inotify_rsync.sh' >> /etc/rc.local              # 设置开机自启动

或者

#!/bin/bash

# 定义脚本中使用的变量
src_dir="/var/www/html"
module_name="wwwroot"
rsync_passwd_file="/etc/server.pass"
target_server1="192.168.1.10"
target_server2="192.168.1.30"
username="backuper"

# 切换到监控目录
cd "${src_dir}" || { echo "Error: Failed to change directory to ${src_dir}"; exit 1; }

# 使用inotifywait监控文件变化
inotifywait -mrq --format '%Xe %w%f' -e modify,create,delete,attrib,close_write,move ./ | while read -r file_event file_path; do
    echo "------------------------------$(date)------------------------------------"
    echo "$file_event $file_path"

    # 根据事件类型执行同步操作
    if [[ "$file_event" =~ (CREATE|MODIFY|CLOSE_WRITE|MOVED_TO) ]]; then
        echo 'CREATE, MODIFY, CLOSE_WRITE or MOVED_TO event detected'
        rsync_cmd=(-avzcR --password-file="${rsync_passwd_file}" "$(dirname "${file_path}")")
        for server in "${target_server1}" "${target_server2}"; do
            rsync "${rsync_cmd[@]}" "${username}@${server}::${module_name}" && echo "Successfully synced with ${server}"
        done
    fi

    if [[ "$file_event" =~ (DELETE|MOVED_FROM) ]]; then
        echo 'DELETE or MOVED_FROM event detected'
        rsync_cmd=(-avzR --delete --password-file="${rsync_passwd_file}" "$(dirname "${file_path}")")
        for server in "${target_server1}" "${target_server2}"; do
            rsync "${rsync_cmd[@]}" "${username}@${server}::${module_name}" && echo "Successfully synced (with deletion) with ${server}"
        done
    fi

    if [[ "$file_event" =~ ATTRIB ]]; then
        echo 'ATTRIB event detected'
        if [[ ! -d "${file_path}" ]]; then
            rsync_cmd=(-avzcR --password-file="${rsync_passwd_file}" "$(dirname "${file_path}")")
            for server in "${target_server1}" "${target_server2}"; do
                rsync "${rsync_cmd[@]}" "${username}@${server}::${module_name}" && echo "Successfully synced due to ATTRIB event with ${server}"
            done
        fi
    fi
done

四、配置rsync+sersync架构

sersync 是基于inotify开发的一个工具,提供了更高级别的封装和管理能力,增强了对inotify监控事件的处理逻辑。

sersync不仅能够监听文件系统的变更,还具备一些额外的功能特性,比如记录详细的日志、支持配置文件定义同步规则、过滤特定类型的文件或目录,以及错误重试机制等。

使用sersync时,用户只需配置其配置文件,当发生文件变更时,sersync会根据配置自动调用rsync进行同步,并且可能包含更复杂的同步策略,比如分批同步、增量同步等。

1、安装sersync

# wget https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/sersync/sersync2.5.4_64bit_binary_stable_final.tar.gz
# tar zxf sersync2.5.4_64bit_binary_stable_final.tar.gz -C /usr/src/
# cd /usr/src/
# mv GNU-Linux-x86/ /usr/src/sersync

2、修改配置文件

# cd sersync/
# cp confxml.xml confxml.xml.bak
# vim confxml.xml
    <sersync>
        <localpath watch="/var/www/html">
            <remote ip="192.168.1.10" name="wwwroot"/>
            <!--<remote ip="192.168.8.39" name="tongbu"/>-->
            <!--<remote ip="192.168.8.40" name="tongbu"/>-->
        </localpath>
        <rsync>
            <commonParams params="-artuz"/>
            <auth start="true" users="backuper" passwordfile="/etc/server.pass"/>
            <userDefinedPort start="false" port="874"/><!-- port=874 -->
            <timeout start="false" time="100"/><!-- timeout=100 -->
            <ssh start="false"/>
        </rsync>
参数说明
watch定义需要监视的本地目录
remote ip定义远程服务器信息
name模块名称(在远程rsync服务器上的路径前缀)
commonParams paramsrsync的通用参数
auth定义rsync的认证信息
userDefinedPort定义自定义rsync端口
timeout设置超时时间
ssh是否使用SSH进行连接

3、启动Sersync

# ./sersync2 -d -r -o ./confxml.xml
set the system param
execute:echo 50000000 > /proc/sys/fs/inotify/max_user_watches
execute:echo 327679 > /proc/sys/fs/inotify/max_queued_events
parse the command param
option: -d 	run as a daemon
option: -r 	rsync all the local files to the remote servers before the sersync work
option: -o 	config xml name:  ./confxml.xml
daemon thread num: 10
parse xml config file
host ip : localhost	host port: 8008
daemon start,sersync run behind the console 
use rsync password-file :
user is	backuper
passwordfile is 	/etc/server.pass
config xml parse success
please set /etc/rsyncd.conf max connections=0 Manually
sersync working thread 12  = 1(primary thread) + 1(fail retry thread) + 10(daemon sub threads) 
Max threads numbers is: 22 = 12(Thread pool nums) + 10(Sub threads)
please according your cpu ,use -n param to adjust the cpu rate
------------------------------------------
rsync the directory recursivly to the remote servers once
working please wait...
execute command: cd /var/www/html && rsync -artuz -R --delete ./ backuper@192.168.1.10::wwwroot --password-file=/etc/server.pass >/dev/null 2>&1 
run the sersync: 
watch path is: /var/www/html
参数说明
-d启用守护进程模式
-r在监控前,将监控目录与远程主机用rsync命令推送一遍
-n指定开启守护线程的数量,默认为10个
-o指定配置文件,默认使用confxml.xml文件
-m单独启用其他模块,使用 -m refreshCDN 开启刷新CDN模块,使用 -m socket 开启socket模块,使用 -m http 开启http模块
-m不加-m参数,则默认执行同步程序

4、设置开机自启

注意:修改文件需要先杀死进程,修改好后再启动

# echo '/usr/src/sersync/sersync2 -d -r -o  /usr/src/sersync/confxml.xml' >> /etc/rc.local              # 设置开机自启动
# killall sersync2 && sersync2 -dro /usr/src/sersync/confxml.xml              # 重启

五、rsync 常见错误与解决方法整理

转载自:https://www.jb51.net/article/31920.htm

查看错误日志,在rsyncd.log里面或.err文件里面或者/var/log/messages里

注意windows下面我们需要给SvcwRsync用户,管理同步目录的所有权限,基本上这样就可以了

1、问题1

@ERROR: chroot failed
rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

服务器端的目录不存在或无权限,创建目录并修正权限可解决问题。

2、问题2

@ERROR: auth failed on module tee
rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

服务器端该模块(tee)需要验证用户名密码,但客户端没有提供正确的用户名密码,认证失败。提供正确的用户名密码解决此问题。

3、问题3

@ERROR: Unknown module ‘tee_nonexists'
rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

服务器不存在指定模块。提供正确的模块名或在服务器端修改成你要的模块以解决问题。

问题4

rsync -auzv --progress --password-file=/etc/rsync.pas root@192.168.133.128::backup /home/
rsync: could not open password file "/etc/rsync.pas": No such file or directory (2)
Password:
@ERROR: auth failed on module backup
rsync error: error starting client-server protocol (code 5) at main.c(1506) [Receiver=3.0.7]

client端没有设置/etc/rsync.pas这个文件,而在使用rsync命令的时候,加了这个参数--password-file=/etc/rsync.pas

问题5

rsync -auzv --progress --password-file=/etc/rsync.pas root@192.168.133.128::backup /home/
@ERROR: auth failed on module backup
rsync error: error starting client-server protocol (code 5) at main.c(1506) [Receiver=3.0.7]

client端已经设置/etc/rsync.pas这个文件,里面也设置了密码111111,和服务器一致,但是服务器段设置有错误,服务器端应该设置/etc/rsync.pas ,里面内容root:111111,这里登陆名不可缺少

问题6

rsync -auzv --progress --password-file=/etc/rsync.pas root@192.168.133.128::backup /home/
@ERROR: chdir failed
rsync error: error starting client-server protocol (code 5) at main.c(1506) [Receiver=3.0.7]

服务器端的/home/backup 其中backup这个目录并没有设置,所以提示:chdir failed

问题7

rsync: write failed on "/home/backup2010/wensong": No space left on device (28)
rsync error: error in file IO (code 11) at receiver.c(302) [receiver=3.0.7]
rsync: connection unexpectedly closed (2721 bytes received so far) [generator]
rsync error: error in rsync protocol data stream (code 12) at io.c(601) [generator=3.0.7]

磁盘空间不够,所以无法操作。可以通过df /home/backup2010 来查看可用空间和已用空间

问题8

rsync: opendir "/kexue" (in dtsChannel) failed: Permission denied (13)

注意查看同步的目录权限是否为755

问题9

rsync: failed to connect to 203.100.192.66: Connection timed out (110)
rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.5]

检查服务器的端口netstat –tunlp,远程telnet测试。可能因为客户端或者服务端的防火墙开启 导致无法通信,可以设置规则放行 rsync(873端口) 或者直接关闭防火墙。还有一种在同步过程中可能会提示没有权限 (将同步目录加上SvcwRsync全部权限即可,更简单的方法就是将SvcwRsync设为管理员即可)

问题10

rsync: failed to connect to 10.10.10.170: Connection refused (111)
rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.5]

启动服务:rsync --daemon --config=/etc/rsyncd.conf

问题11

rsync: recv_generator: mkdir "/teacherclubBackup/rsync……" failed: No space left on device (28)

磁盘空间满

问题12

rsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(544) [receiver=3.0.5]
rsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(544) [generator=3.0.5]

导致此问题多半是服务端服务没有被正常启动,到服务器上去查查服务是否有启动,然后查看下 /var/run/rsync.pid 文件是否存在,最干脆的方法是杀死已经启动了服务,然后再次启动服务或者让脚本加入系统启动服务级别然后shutdown -r now服务器

问题13

rsync: read error: Connection reset by peer (104)
rsync error: error in rsync protocol data stream (code 12) at io.c(759) [receiver=3.0.5]

查看rsync日志

rsync: unable to open configuration file "/etc/rsyncd.conf": No such file or directory

xnetid查找的配置文件位置默认是/etc下,根据具体情况创建软链接。例如:

ln -s /etc/rsyncd/rsyncd.conf /etc/rsyncd.conf

或者更改指定默认的配置文件路径,在/etc/xinetd.d/rsync配置文件中。

问题14

ignore errors

用于指示在同步过程中遇到错误时是否继续执行。这个选项最好加上,否则再很多crontab的时候往往发生错误你也未可知,因为你不可能天天去看每时每刻去看log,不加上这个出现错误的几率相对会很高,因为任何大点的项目和系统,磁盘IO都是一个瓶颈

问题15

@ERROR: auth failed on module xxxxx
rsync: connection unexpectedly closed (90 bytes read so far)
rsync error: error in rsync protocol data stream (code 12) at io.c(150)

这是因为密码设置错了,无法登入成功,检查一下rsync.pwd,看客服是否匹配。还有服务器端没启动rsync 服务也会出现这种情况

问题16

password file must not be other-accessible
continuing without password file
Password:

这是因为rsyncd.pwd rsyncd.sec的权限不对,应该设置为600。如:chmod 600 rsyncd.pwd

问题17

@ERROR: chroot failed
rsync: connection unexpectedly closed (75 bytes read so far)
rsync error: error in rsync protocol data stream (code 12) at io.c(150)

这是因为你在 rsync.conf 中设置的 path 路径不存在,要新建目录才能开启同步

问题18

rsync: failed to connect to 218.107.243.2: No route to host (113)
rsync error: error in socket IO (code 10) at clientserver.c(104) [receiver=2.6.9]

防火墙问题导致,这个最好先彻底关闭防火墙,排错的基本法就是这样,无论是S还是C,还有ignore errors选项问题也会导致

问题19

@ERROR: access denied to www from unknown (192.168.1.123)
rsync: connection unexpectedly closed (0 bytes received so far) [receiver]
rsync error: error in rsync protocol data stream (code 12) at io.c(359)

说明:此问题很明显,是配置选项host allow的问题,初学者喜欢一个允许段做成一个配置,然后模块又是同一个,致使导致

问题20

rsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(244) [generator=2.6.9]
rsync error: received SIGUSR1 (code 19) at main.c(1182) [receiver=2.6.9]

导致此问题多半是服务端服务没有被正常启动,到服务器上去查查服务是否有启动,然后查看下 /var/run/rsync.pid 文件是否存在,最干脆的方法是杀死已经启动了服务,然后再次启动服务或者让脚本加入系统启动服务级别然后shutdown -r now服务器

问题21

rsync: read error: Connection reset by peer (104)
rsync error: error in rsync protocol data stream (code 12) at io.c(604) [sender=2.6.9]

原数据目录里没有数据存在

问题22

@ERROR: auth failed on module bachup
 rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

服务器端该模块(backup)需要验证用户名密码,但客户端没有提供正确的用户名密码,认证失败。 提供正确的用户名密码解决此问题。

这个问题比较蠢,如果可能你和我一样明明在模块里写了密码文件,怎么都不通,这个时候我劝你先检查一下所写模块中是不是和下图一样。比如,某处多了个s。

img

问题23

rsync: failed to connect to 203.100.192.66: Connection timed out (110) 
rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.5]

检查服务器的端口netstat –tunlp,远程telnet测试。 可能因为客户端或者服务端的防火墙开启 导致无法通信,可以设置规则放行 rsync(873端口) 或者直接关闭防火墙。

在这里博主是重启过服务器,然后就报110了,直接开启rsync服务就行。

问题24

rsync: failed to connect to 218.107.243.2: No route to host (113) rsync error: error in socket IO (code 10) at clientserver.c(104) [receiver=2.6.9]

防火墙问题导致,这个很简单,关闭防火墙就可以。

问题25

@ERROR: auth failed on module backup
rsync error: error starting client-server protocol (code 5) at main.c(1516) [Receiver=3.0.9]

img

解决:这个问题错误差别很大,可查看系统日志查看错误,再搜索解决方法。

注意:一般这种情况都建立在可以连通的基础。去服务端查看系统日志,可以查看相关错误。

cat /var/log/massages
cat /var/log/rsyncd.log
0

评论区