简介
rsync是linux系统下的数据镜像备份工具。使用快速增量备份工具Remote Sync可以远程同步,支持本地复制,或者与其他SSH、rsync主机同步。
原理:
-
Rsync本来是用于替代rcp的一个工具,目前由rsync.samba.org维护,所以rsync.conf文件的格式类似于samba的主配 置文件;Rsync可以通过rsh或ssh使用,也能以daemon模式去运行
-
在以daemon方式运行时Rsync server会打开一个873 端口,等待客户端去连接。连接时,Rsync server会检查口令是否相符,若通过口令查核,则可以开始进行文件传输。第一次连通完成时,会把整份文件传输一次,以后则就只需进行增量备份
rsync特性
- 可以镜像保存整个目录树和文件系统
- 可以很容易做到保持原来文件的权限、时间、软硬链接等等
- 无须特殊权限即可安装
- 快速:第一次同步时rsync会复制全部内容,但在下一次只传输修改过的文件。rsync在传输数据的过程中可以实行压缩及解压缩操作,因此可以使用更少的带宽
- 安全:可以使用scp、ssh等方式来传输文件,当然也可以通过直接的socket连接
- 支持匿名传输,以方便进行网站镜像
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打通通道
rsync -avz /SRC -e ssh root@IP:/DEST
-a #文件宿主变化,时间戳不变
-z #压缩数据传输
#当端口被修改时时:
rsync -avz /SRC -e "ssh -p 2222" root@IP:/DRST
# 修改了ssh协议端口,默认22
srync命令
#常用选项
-a #归档
-v #啰嗦模式
-q #静默模式
-r #递归
-p #保持原有的权限属性
-z #在传输时压缩,节省带宽,加快传输速度
#rsync命令格式:
rsync [OPTION]...SRC DEST
rsync [OPTION]...SRC [user@]HOST:DEST
rsync [OPTION]... [user@]HOST:SRC DEST
#拷贝本地文件
[root@localhost ~]# ls /opt/
[root@localhost ~]# rsync -avz anaconda-ks.cfg /opt/
sending incremental file list
anaconda-ks.cfg
sent 885 bytes received 35 bytes 1,840.00 bytes/sec
total size is 1,344 speedup is 1.46
[root@localhost ~]# ls /opt/
anaconda-ks.cfg
#将本地内容拷贝到目标主机上
[root@localhost ~]# rsync -avz anaconda-ks.cfg root@192.168.8.132:/opt/
The authenticity of host '192.168.8.132 (192.168.8.132)' can't be established.
ECDSA key fingerprint is SHA256:S7JN98WokZIDsafG+oMQFmaLdrE7jMF2IYzUN3IevqM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.8.132' (ECDSA) to the list of known hosts.
root@192.168.8.132's password:
sending incremental file list
anaconda-ks.cfg
sent 885 bytes received 35 bytes 262.86 bytes/sec
total size is 1,344 speedup is 1.46
[root@132 ~]# ls /opt/
anaconda-ks.cfg
#将远程主机的内容拷贝到本地上
[root@localhost ~]# rsync -avz root@192.168.8.132:/opt/TEST /root/
root@192.168.8.132's password:
receiving incremental file list
TEST
sent 43 bytes received 83 bytes 50.40 bytes/sec
total size is 0 speedup is 0.00
[root@localhost ~]# ls
anaconda-ks.cfg lamp——shell TEST
rsync+inotify
rsync与传统的cp、tar备份方式相比,rsync具有安全性高、备份迅速、支持增量备份等优点,通过rsync可以解决对实时性要求不高的数据备份需求,例如定期的备份文件服务器数据到远端服务器,对本地磁盘定期做数据镜像等。
随着应用系统规模的不断扩大,对数据的安全性和可靠性也提出的更好的要求,rsync在高端业务系统中也逐渐暴露出了很多不足,首先,rsync同步数据时,需要扫描所有文件后进行比对,进行差量传输。如果文件数量达到了百万甚至千万量级,扫描所有文件将是非常耗时的。而且正在发生变化的往往是其中很少的一部分,这是非常低效的方式。其次,rsync不能实时的去监测、同步数据,虽然它可以通过linux守护进程的方式进行触发同步,但是两次触发动作一定会有时间差,这样就导致了服务端和客户端数据可能出现不一致,无法在应用故障时完全的恢复数据。
Inotify是一种强大的、细粒度的、异步的文件系统事件监控机制,linux内核从2.6.13起,加入了Inotify支持,通过Inotify可以监控文件系统中添加、删除,修改、移动等各种细微事件,利用这个内核接口,第三方软件就可以监控文件系统下文件的各种变化情况,而inotify-tools就是这样的一个第三方软件。
在前面有讲到,rsync可以实现触发式的文件同步,但是通过crontab守护进程方式进行触发,同步的数据和实际数据会有差异,而inotify可以监控文件系统的各种变化,当文件有任何变动时,就触发rsync同步,这样刚好解决了同步数据的实时性问题。
环境:
服务器类型 | IP地址 | 应用 |
---|---|---|
源服务器 | 192.168.8.132 | rsync inotify-tools scripts |
目标服务器 | 192.168.8.129 | rsync |
目标服务器上操作:
#安装rsync服务端软件,(需关闭防火墙与SELINUX)
[root@localhost ~]# yum -y install rsync-daemon
[root@localhost ~]# yum -y install rsync
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
上次元数据过期检查:0:09:10 前,执行于 2021年10月11日 星期一 14时59分17秒。
依赖关系解决。
=================================================================================================================================================
软件包 架构 版本 仓库 大小
=================================================================================================================================================
安装:
rsync x86_64 3.1.3-12.el8
······
#设置rsyncd.conf配置文件
[root@localhost ~]# cat >> /etc/rsyncd.conf <<EOF
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 = /tmp/ # 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 = 172.16.12.128 # 允许进行数据同步的客户端IP地址,可以设置多个,用英文状态下逗号隔开
hosts deny = 192.168.1.1 # 禁止数据同步的客户端IP地址,可以设置多个,用英文状态下逗号隔开
EOF
#创建用户认证文件
[root@localhost ~]# echo 'admin:123' > /etc/rsync.pass
#设置文件权限
[root@localhost ~]# chmod 600 /etc/rsync*
[root@localhost ~]# ll /etc/rsync*
-rw------- 1 root root 337 10月 11 15:28 /etc/rsyncd.conf
-rw------- 1 root root 10 10月 11 15:29 /etc/rsync.pass
[root@localhost ~]# systemctl enable --now rsyncd
Created symlink /etc/systemd/system/multi-user.target.wants/rsyncd.service → /usr/lib/systemd/system/rsyncd.service.
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 5 0.0.0.0:873 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 5 [::]:873 [::]:*
源服务器上操作:
#配置yum源
[root@132 ~]# yum -y install epel-release
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
上次元数据过期检查:0:16:23 前,执行于 2021年10月11日 星期一 23时18分49秒。
依赖关系解决。
=================================================================================================================================================
软件包 架构 版本 仓库 大小
=================================================================================================================================================
安装:
epel-release noarch 8-11.el8
······
# 安装inotify-tools
[root@132 ~]# yum -y install inotify-tools
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
上次元数据过期检查:0:43:20 前,执行于 2021年10月11日 星期一 14时59分17秒。
依赖关系解决。
=================================================================================================================================================
软件包 架构 版本 仓库 大小
=================================================================================================================================================
安装:
inotify-tools x86_64 3.14-19.el8
#创建认证密码文件
[root@132 ~]# echo '123' > /etc/rsync.pass
[root@132 ~]# chmod 600 /etc/rsync.pass
#创建测试目录
[root@132 ~]# mkdir /opt/test
[root@132 ~]# rsync -avH --port 873 --progress --delete /opt/test/ admin@192.168.8.129::etc_from_client --password-file=/etc/rsync.pass
sending incremental file list
deleting vmware-root_968-2965448017/
deleting vmware-root_961-4248090753/
deleting vmware-root_1001-4282302135/
deleting .font-unix/
deleting .XIM-unix/
deleting .X11-unix/
deleting .Test-unix/
deleting .ICE-unix/
deleting ks-script-d1hrrkc2
deleting anaconda-ks.cfg
./
sent 51 bytes received 230 bytes 187.33 bytes/sec
total size is 0 speedup is 0.00
[root@132 ~]# ls /tmp/
test
[root@132 ~]# vim /scripts/inotify.sh
host=172.16.12.129 # 目标服务器的ip(备份服务器)
src=/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
#启动脚本
[root@132 ~]# nohup /scrpits/inotify.sh &
[1] 2568
[root@132 ~]# nohup: ignoring input and appending output to 'nohup.out'
设置脚本开机自启
[root@132 ~]# chmod +x /etc/rc.d/rc.local
[root@132 ~]# cat /etc/rc.d/rc.local
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# 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.
nohup /scripts/inotify.sh &
touch /var/lock/subsys/local
#查看目标主机
[root@localhost ~]# ls /tmp/etc/
adjtime dhcp hostname lvm pm rwtab.d system-release
aliases DIR_COLORS hosts machine-id polkit-1 sasl2 system-release-cpe
alternatives DIR_COLORS.256color idmapd.conf magic popt.d security tcsd.conf
anacrontab DIR_COLORS.lightbgcolor init.d makedumpfile.conf.sample prelink.conf.d selinux terminfo
audit dnf inittab man_db.conf printcap services testone
authselect dracut.conf inputrc microcode_ctl profile sestatus.conf tmpfiles.d
bash_completion.d dracut.conf.d iproute2 mke2fs.conf profile.d shadow tuned
bashrc environment issue modprobe.d protocols shadow- udev
bindresvport.blacklist ethertypes issue.net modules-load.d rc0.d shells unbound
binfmt.d exports kdump.conf motd rc1.d skel vconsole.conf
chkconfig.d filesystems kernel mtab rc2.d ssh vimrc
cifs-utils firewalld krb5.conf netconfig rc3.d ssl virc
cron.d fstab krb5.conf.d NetworkManager rc4.d sssd vmware-tools
cron.daily fuse.conf ld.so.cache networks rc5.d subgid X11
cron.deny gcrypt ld.so.conf nftables rc6.d subgid- xattr.conf
cron.hourly gnupg ld.so.conf.d nsswitch.conf rc.d subuid xdg
cron.monthly GREP_COLORS libaudit.conf nsswitch.conf.bak rc.local subuid- xinetd.d
crontab groff libnl openldap redhat-release sudo.conf yum
cron.weekly group libreport opt resolv.conf sudoers yum.conf
crypto-policies group- libssh os-release rhsm sudoers.d yum.repos.d
crypttab grub2.cfg libuser.conf pam.d rpc sudo-ldap.conf
csh.cshrc grub.d locale.conf passwd rpm swid
csh.login gshadow localtime passwd- rsyncd.conf sysconfig
dbus-1 gshadow- login.defs pkcs11 rsync.pass sysctl.conf
default gss logrotate.conf pki rsyslog.conf sysctl.d
depmod.d host.conf logrotate.d plymouth rsyslog.d systemd