rsync的介绍和配置

rsync的介绍和配置


rsync简介

rsync官方网站:https://rsync.samba.org/

英文全称为Remote synchronization服务软件,缩写rsync

Rsync 是一款开源的快速的 多功能的 可以实现全量以及增量本地或者是远程数据同步(拷贝)备份的优秀工具

rsync是linux系统下的数据镜像备份工具。使用快速增量备份工具Remote Sync可以远程同步,支持本地复制,或者与其他SSHrsync主机同步。

目前,已支持跨平台,可以在Windows与Linux间进行数据同步.


rsync服务器架构

rsync服务器架设比较简单,可能我们安装好rsync后,并没有发现配置文件,以及rsync服务器启动程序,因为每个管理员可能对rsync用途不一样,所以一般的发行版只是安装好软件就完事了,让管理员来根据自己的用途和方向来自己架设rsync服务器;因为这个rsync应用比较广,能在同一台主机进行备份工作,还能在不同主机之间进行工作。在不同主机之间的进行备份,是必须架设rsync服务器的。

在远程同步任务中,负责发起rsync同步操作的客户机称为发起端,而负责响应来自客机的rsync同步操作的服务器称为备份源。在下行同步(下载)中,备份源负责提供文档的原始位置,发起端应对该位置具有读取权限;在上行同步(上传)中,备份源负责提供文档的目标位置,发起端应对该位置具有写入权限。如下图所示:

1


rsync特性

rsync支持很多特性:

  • 可以镜像保存整个目录树和文件系统文件系统。
  • 可以很容易做到保持原来文件的权限、时间、软硬链接等等。
  • 无须特殊权限即可安装。
  • 快速:第一次同步时 rsync 会复制全部内容,但在下一次只传输修改过的文件。rsync在传输数据的过程中可以实行压缩及解压缩解压缩)操作,因此可以使用更少的带宽。
  • 安全:可以使用scpssh等方式来传输文件,当然也可以通过直接的socket连接。
  • 支持匿名传输,以方便进行网站镜像。

总结:一个rsync命令相当于scp、cp、rm命令,但是rsync命令比scp、cp、rm命令更胜一筹。


rsync工作方式

一般来说,rsync大致使用三种工作方式来传输数据,分别为:

  1. 本地文件系统上实现同步;单个主机本地之间的数据传输(此时类似于cp命令的功能)
  2. 本地主机使用远程shell和远程主机通信;借助rcp,ssh等通道来传输数据(此时类似于 scp命令的功能)
  3. 本地主机通过网络套接字连接远程主机上的rsync daemon;以守护进程(socket)的方式传输数据(这个是rsync自身的重要的功能)

rsync的ssh认证协议

rsync命令来同步系统文件之前要先登录remote主机认证,认证过程中用到的协议有2种:

  • ssh协议
  • rsync协议
rsync server`端不用启动`rsync`的`daemon`进程,只要获取`remote host`的用户名和密码就可以直接`rsync`同步文件
`rsync server`端因为不用启动`daemon`进程,所以也不用配置文件`/etc/rsyncd.conf

ssh认证协议跟scp的原理是一样的,如果在同步过程中不想输入密码就用ssh-keygen -t rsa打通通道

//这种方式默认是省略了 -e ssh 的,与下面等价:
rsync -avz /SRC -e ssh root@192.168.100.10:/DEST 
    -a  //文件宿主变化,时间戳不变
    -V  //显示详细信息的过程
    -z  //压缩数据传输

//当遇到要修改端口的时候,我们可以:
#修改了ssh 协议的端口,默认是22
rsync -avz /SRC -e "ssh -p2222" root@192.168.100.1:/DEST  

rsync命令

安装rsync

[root@node1 ~]# yum -y install rsync

rsync命令格式

//Rsync的命令格式常用的有以下三种:
    rsync [OPTION]... SRC DEST
    rsync [OPTION]... SRC [USER@]HOST:DEST
    rsync [OPTION]... [USER@]HOST:SRC DEST

//对应于以上三种命令格式,rsync有三种不同的工作模式:
1)拷贝本地文件。当SRC和DES路径信息都不包含有单个冒号":"分隔符时就启动这种工作模式.
#命令示例
[root@node1 ~]# rsync -avz abc /opt/123
2)使用一个远程shell程序(如rsh、ssh)来实现将本地机器的内容拷贝到远程机器。当DST路径地址包 
含单个冒号":"分隔符时启动该模式。
#命令示例
[root@node1 ~]# ssh root@192.168.100.2 'ls -l /root'
3)使用一个远程shell程序(如rsh、ssh)来实现将远程机器的内容拷贝到本地机器。当SRC地址路径 
包含单个冒号":"分隔符时启动该模式。
#命令示例
[root@node1 ~]# rsync -avz root@192.168.100.2:/etc/yum.repos.d /root/

rsync命令参数详情

-v, --verbose         详细模式输出
-q, --quiet           精简输出模式
-c, --checksum        打开校验开关,强制对文件传输进行校验
-a, --archive         归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD
-r, --recursive       对子目录以递归模式处理
-R, --relative        使用相对路径信息
-b, --backup          创建备份,也就是对于目的已经存在有同样的文件名时,将老的文件重新命名为~filename。可以使用--suffix选项来指定不同的备份文件前缀。
--backup-dir          将备份文件(如~filename)存放在在目录下。
-suffix=SUFFIX        定义备份文件前缀
-u, --update          仅仅进行更新,也就是跳过所有已经存在于DST,并且文件时间晚于要备份的文件。(不覆盖更新的文件)
-l, --links           保留软链结
-L, --copy-links      像对待常规文件一样处理软链接
--copy-unsafe-links   仅仅拷贝指向SRC路径目录树以外的链接
--safe-links          忽略指向SRC路径目录树以外的链接
-H, --hard-links      保留硬链接
-p, --perms           保持文件权限
-o, --owner           保持文件属主信息
-g, --group           保持文件属组信息
-D, --devices         保持设备文件信息
-t, --times           保持文件时间信息
-S, --sparse          对稀疏文件进行特殊处理以节省DST的空间
-n, --dry-run         显示哪些文件将被传输
-W, --whole-file      拷贝文件,不进行增量检测
-x, --one-file-system 不要跨越文件系统边界
-B, --block-size=SIZE 检验算法使用的块尺寸,默认是700字节
-e, --rsh=COMMAND     指定使用rsh、ssh方式进行数据同步
--rsync-path=PATH     指定远程服务器上的rsync命令所在路径信息
-C, --cvs-exclude     使用和CVS一样的方法自动忽略文件,用来排除那些不希望传输的文件
--existing            仅仅更新那些已经存在于DST的文件,而不备份那些新创建的文件
--delete              删除那些DST中SRC没有的文件
--delete-excluded     同样删除接收端那些被该选项指定排除的文件
--delete-after        传输结束以后再删除
--ignore-errors       即使出现IO错误也进行删除
--max-delete=NUM      最多删除NUM个文件
--partial             保留那些因故没有完全传输的文件,以是加快随后的再次传输
--force               强制删除目录,即使不为空
--numeric-ids         不将数字的用户和组ID匹配为用户名和组名
--timeout=TIME        IP超时时间,单位为秒
-I, --ignore-times    不跳过那些有同样的时间和长度的文件
--size-only           当决定是否要备份文件时,仅仅察看文件大小而不考虑文件时间
--modify-window=NUM   决定文件是否时间相同时使用的时间戳窗口,默认为0
-T --temp-dir=DIR     在DIR中创建临时文件
--compare-dest=DIR    同样比较DIR中的文件来决定是否需要备份
-P                    等同于 --partial
--progress            显示备份过程
-z, --compress        对备份的文件在传输时进行压缩处理
--exclude=PATTERN     指定排除不需要传输的文件模式
--include=PATTERN     指定不排除而需要传输的文件模式
--exclude-from=FILE   排除FILE中指定模式的文件
--include-from=FILE   不排除FILE指定模式匹配的文件
--version             打印版本信息
--address             绑定到特定的地址
--config=FILE         指定其他的配置文件,不使用默认的rsyncd.conf文件
--port=PORT           指定其他的rsync服务端口
--blocking-io         对远程shell使用阻塞IO
-stats                给出某些文件的传输状态
--progress            在传输时显示传输过程
--log-format=formAT   指定日志文件格式
--password-file=FILE  从FILE中得到密码
--bwlimit=KBPS        限制I/O带宽,KBytes per second
-h, --help            显示帮助信息

rsync配置

本次环境为:

主机名 IP地址 安装的应用 系统版本
node1 192.168.100.1 rsync RedHat 8
node2 192.168.100.2 rsync RedHat 8

准备工作:

#node1:
[root@node1 ~]# systemctl disable --now firewalld
[root@node1 ~]# sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
[root@node1 ~]# setenforce 0
[root@node1 ~]# yum -y install rsync

#node2:
[root@node2 ~]# systemctl disable --now firewalld
[root@node2 ~]# sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
[root@node2 ~]# setenforce 0
[root@node2 ~]# yum -y install rsync

ssh协议本地同步

注意:如果目的地没有这个文件,系统会自动创建这个文件,如果有这个文件只会同步不一样的内容。

#node1
//同步文件或目录
[root@node1 ~]# mkdir project
[root@node1 ~]# echo 'this is a file' > project/file
[root@node1 ~]# ls project/
file

//把file文件和project目录同步到/opt下
[root@node1 ~]# rsync -avz project/file project /opt/
sending incremental file list
file
project/
project/file

sent 217 bytes  received 62 bytes  558.00 bytes/sec
total size is 30  speedup is 0.11

//验证
[root@node1 ~]# ls /opt/
file  project
[root@node1 ~]# ll project/file /opt/file /opt/project/file 
-rw-r--r--. 1 root root 15 May 10 21:03 /opt/file
-rw-r--r--. 1 root root 15 May 10 21:03 /opt/project/file
-rw-r--r--. 1 root root 15 May 10 21:03 project/file
[root@node1 ~]# cat file /opt/file /opt/project/file 
this is a file
this is a file
this is a file

ssh协议非本地同步

#node1
[root@node1 ~]# ls
anaconda-ks.cfg  file  project

//把node1上的file文件和project目录同步到node2的/opt下
[root@node1 ~]# rsync -avz project/file project root@192.168.100.2:/opt/
root@192.168.100.2's password: 
sending incremental file list
file
project/
project/file

sent 221 bytes  received 66 bytes  82.00 bytes/sec
total size is 30  speedup is 0.10

#node2
//验证
[root@node2 ~]# ls /opt/
file  project
[root@node2 ~]# ll /opt/file /opt/project/file 
-rw-r--r--. 1 root root 15 May 10 21:03 /opt/file
-rw-r--r--. 1 root root 15 May 10 21:03 /opt/project/file
[root@node2 ~]# cat /opt/file /opt/project/file 
this is a file
this is a file

rsync自动同步

rsync与传统的cptar备份方式相比,rsync具有安全性高、备份迅速、支持增量备份等优点,通过rsync可以解决对实时性要求不高的数据备份需求,例如定期的备份文件服务器数据到远端服务器,对本地磁盘定期做数据镜像等。
随着应用系统规模的不断扩大,对数据的安全性和可靠性也提出的更好的要求,rsync在高端业务系统中也逐渐暴露出了很多不足,首先,rsync同步数据时,需要扫描所有文件后进行比对,进行差量传输。如果文件数量达到了百万甚至千万量级,扫描所有文件将是非常耗时的。而且正在发生变化的往往是其中很少的一部分,这是非常低效的方式。其次,rsync不能实时的去监测、同步数据,虽然它可以通过linux守护进程的方式进行触发同步,但是两次触发动作一定会有时间差,这样就导致了服务端和客户端数据可能出现不一致,无法在应用故障时完全的恢复数据。基于以上原因,rsync+inotify组合出现了!

Inotify是一种强大的、细粒度的、异步的文件系统事件监控机制,linux内核从2.6.13起,加入了Inotify支持,通过Inotify可以监控文件系统中添加、删除,修改、移动等各种细微事件,利用这个内核接口,第三方软件就可以监控文件系统下文件的各种变化情况,而inotify-tools就是这样的一个第三方软件。
在前面有讲到,rsync可以实现触发式的文件同步,但是通过crontab守护进程方式进行触发,同步的数据和实际数据会有差异,而inotify可以监控文件系统的各种变化,当文件有任何变动时,就触发rsync同步,这样刚好解决了同步数据的实时性问题。

配置文件说明

log file = /var/log/rsyncd.log    # 日志文件位置,启动rsync后自动产生这个文件,无需提前创建
pidfile = /var/run/rsyncd.pid     # pid文件的存放位置
lock file = /var/run/rsync.lock   # 支持max connections参数的锁文件
secrets file = /etc/rsync.pass    # 用户认证配置文件,里面保存用户名称和密码,必须手动创建这个文件

[etc_from_client]                 # 自定义同步名称
path = /opt/                      # rsync目标服务端数据存放路径,源服务器的数据将同步至此目录
comment = sync etc from client
uid = root                        # 设置rsync运行权限为root
gid = root                        # 设置rsync运行权限为root
port = 873                        # 默认端口
ignore errors                     # 表示出现错误忽略错误
use chroot = no                   # 默认为true,修改为no,增加对目录文件软连接的备份
read only = no                    # 设置rsync服务端为读写权限
list = no                         # 不显示rsync服务端资源列表
max connections = 200             # 最大连接数
timeout = 600                     # 设置超时时间
auth users = admin                # 执行数据同步的用户名,可以设置多个,用英文状态下逗号隔开
hosts allow = 192.168.1.1         # 允许进行数据同步的源服务器IP地址,可以设置多个,用英文状态下逗号隔开
hosts deny = 192.168.1.1          # 禁止数据同步的源服务器IP地址,可以设置多个,用英文状态下逗号隔开

本次环境为:

服务器类型 主机名 IP地址 安装的应用 系统版本
源服务器 node1 192.168.100.3 rsync inotify-tools RedHat 8
目标服务器 node2 192.168.100.4 rsync RedHat 8

需求:

  • 把源服务器上/opt目录实时同步到目标服务器的/opt/下

准备工作:

#node1:
[root@node1 ~]# systemctl disable --now firewalld
[root@node1 ~]# sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
[root@node1 ~]# setenforce 0
[root@node1 ~]# yum -y install rsync

#node2:
[root@node2 ~]# systemctl disable --now firewalld
[root@node2 ~]# sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
[root@node2 ~]# setenforce 0
[root@node2 ~]# yum -y install rsync

在node1上创建用于同步的测试文件

#node1
[root@node1 ~]# cd /opt/
[root@node1 opt]# mkdir dir{1..3}
[root@node1 opt]# touch dir1/file{1..3} dir2/file{1..3} dir3/file{1..3}
[root@node1 opt]# tree /opt/
/opt/
├── dir1
│   ├── file1
│   ├── file2
│   └── file3
├── dir2
│   ├── file1
│   ├── file2
│   └── file3
└── dir3
    ├── file1
    ├── file2
    └── file3

3 directories, 9 files

配置目标服务器

#node2
//设置rsyncd.conf配置文件
[root@node2 ~]# vim /etc/rsyncd.conf
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 = /opt/          
comment = sync etc from client
uid = root
gid = root        
port = 873        
ignore errors     
use chroot = no       
read only = no    
list = no     
max connections = 200     
timeout = 600     
auth users = admin

//创建用户认证文件
[root@node2 ~]# echo 'admin:123456' > /etc/rsync.pass
[root@node2 ~]# cat /etc/rsync.pass
admin:123456

//设置文件权限
[root@node2 ~]# chmod 600 /etc/rsync*
[root@node2 ~]# ll /etc/rsync*
-rw-------. 1 root root 1145 May 11 14:56 /etc/rsyncd.conf
-rw-------. 1 root root   13 May 11 14:57 /etc/rsync.pass

//启动rsync服务
[root@node2 ~]# rsync --daemon
[root@node2 ~]# ss -antl
State     Recv-Q    Send-Q       Local Address:Port        Peer Address:Port    
LISTEN    0         128                0.0.0.0:22               0.0.0.0:*       
LISTEN    0         5                  0.0.0.0:873              0.0.0.0:*       
LISTEN    0         128                   [::]:22                  [::]:*       
LISTEN    0         5                     [::]:873                 [::]:*  

配置源服务器

#node1
//创建认证密码文件
[root@node1 ~]# echo '123456' > /etc/rsync.pass
[root@node1 ~]# cat /etc/rsync.pass
123456

//设置文件权限,只设置文件所有者具有读取、写入权限即可
[root@node1 ~]# chmod 600 /etc/rsync.pass
[root@node1 ~]# ll /etc/rsync.pass
-rw------- 1 root root 7 May 11 15:01 /etc/rsync.pass

[root@node1 ~]# rsync -avH --port 873 --progress --delete /opt admin@192.168.100.4::etc_from_client --password-file=/etc/rsync.pass
sending incremental file list
opt/
opt/dir1/
opt/dir1/file1
              0 100%    0.00kB/s    0:00:00 (xfr#1, to-chk=8/13)
opt/dir1/file2
              0 100%    0.00kB/s    0:00:00 (xfr#2, to-chk=7/13)
opt/dir1/file3
              0 100%    0.00kB/s    0:00:00 (xfr#3, to-chk=6/13)
opt/dir2/
opt/dir2/file1
              0 100%    0.00kB/s    0:00:00 (xfr#4, to-chk=5/13)
opt/dir2/file2
              0 100%    0.00kB/s    0:00:00 (xfr#5, to-chk=4/13)
opt/dir2/file3
              0 100%    0.00kB/s    0:00:00 (xfr#6, to-chk=3/13)
opt/dir3/
opt/dir3/file1
              0 100%    0.00kB/s    0:00:00 (xfr#7, to-chk=2/13)
opt/dir3/file2
              0 100%    0.00kB/s    0:00:00 (xfr#8, to-chk=1/13)
opt/dir3/file3
              0 100%    0.00kB/s    0:00:00 (xfr#9, to-chk=0/13)

sent 622 bytes  received 211 bytes  1,666.00 bytes/sec
total size is 0  speedup is 0.00

//运行完成后,在目标服务器上查看,在/opt目录下有dir目录,说明数据同步成功
#node2
[root@node2 ~]# tree /opt/
/opt/
└── opt
    ├── dir1
    │   ├── file1
    │   ├── file2
    │   └── file3
    ├── dir2
    │   ├── file1
    │   ├── file2
    │   └── file3
    └── dir3
        ├── file1
        ├── file2
        └── file3

4 directories, 9 files

实时触发rsync进行同步

#node1
//查看服务器内核是否支持inotify
[root@node1 ~]# ll /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 May 11 15:22 max_queued_events
-rw-r--r-- 1 root root 0 May 11 15:22 max_user_instances
-rw-r--r-- 1 root root 0 May 11 15:22 max_user_watches

#如果有这三个max开头的文件则表示服务器内核支持inotify

//安装inotify-tools工具
[root@node1 ~]# yum -y install inotify-tools

//写同步脚本
[root@node1 ~]# mkdir /scripts
[root@node1 ~]# vim /scripts/inotify.sh
#/bin/bash
host=192.168.100.4                 # 目标服务器的ip(备份服务器)
src=/opt                           # 在源服务器上所要监控的备份目录(此处可以自定义,但是要保证存在)
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

[root@node1 ~]# chmod 755 /scripts/inotify.sh
[root@node1 ~]# ll /scripts/inotify.sh
-rwxr-xr-x 1 root root 718 May 11 15:26 /scripts/inotify.sh

//启动脚本
[root@node1 ~]# nohup bash /scripts/inotify.sh &
[1] 2718
nohup: ignoring input and appending output to 'nohup.out'

[root@node1 ~]# ps -ef|grep inotify
root        2718    1503  0 15:35 pts/0    00:00:00 bash /scripts/inotify.sh
root        2719    2718  0 15:35 pts/0    00:00:00 /usr/bin/inotifywait -mrq --timefmt %Y%m%d %H:%M --format %T %w%f%e -e modify,delete,create,attrib /opt
root        2720    2718  0 15:35 pts/0    00:00:00 bash /scripts/inotify.sh
root        2722    1503  0 15:36 pts/0    00:00:00 grep --color=auto inotify

//在源服务器上生成一个新文件
[root@node1 ~]# echo 'this is a file' > /opt/test

//查看inotify生成的日志
[root@node1 ~]# tail /tmp/rsync.log 
20210511 15:39 /opt/testCREATE was rsynced
20210511 15:39 /opt/testMODIFY was rsynced
#从日志上可以看到,我们生成了一个test文件,并且添加了内容到其里面

到目标服务器查看是否同步

#node2
[root@node2 ~]# ll /opt/opt/
total 4
drwxr-xr-x. 2 root root 45 May 11 14:16 dir1
drwxr-xr-x. 2 root root 45 May 11 14:16 dir2
drwxr-xr-x. 2 root root 45 May 11 14:16 dir3
-rw-r--r--. 1 root root 15 May 11 15:39 test
[root@node2 ~]# cat /opt/opt/test 
this is a file

设置脚本开机自动启动

[root@node1 ~]# chmod +x /etc/rc.d/rc.local
[root@node1 ~]# ll /etc/rc.d/rc.local
-rwxr-xr-x. 1 root root 474 Mar 24  2020 /etc/rc.d/rc.local
[root@node1 ~]# echo 'nohup /bin/bash /scripts/inotify.sh' >> /etc/rc.d/rc.local
[root@node1 ~]# 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 /scripts/inotify.sh

在目标服务器中设置rsync的开机自启动

#node2
//编写rsyncd.service文件
[root@node2 ~]# vim /usr/lib/systemd/system/rsyncd.service
[Unit]
Description=fast remote file copy program daemon
ConditionPathExists=/etc/rsyncd.conf

[Service]
EnvironmentFile=/etc/sysconfig/rsyncd
ExecStart=/usr/bin/rsync --daemon --no-detach "$OPTIONS"

[Install]
WantedBy=multi-user.target
[root@node2 ~]# echo 'OPTIONS=""' > /etc/sysconfig/rsyncd

//设置开机自启动
[root@node2 ~]# systemctl enable --now rsyncd
原文地址:https://www.cnblogs.com/yuqinghao/p/14752962.html