rsync(远程同步)

rsync(远程同步)

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

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打通通道

//这种方式默认是省略了 -e ssh 的,与下面等价:
rsync -avz /SRC(目录) -e ssh root@172.16.12.129(主机):/DEST(目标位置) 
    -a  //文件宿主变化,时间戳不变
    -v  //显示传输过程
    -z  //压缩数据传输
 
//当遇到要修改端口的时候,我们可以:
rsync -avz /SRC -e "ssh -p2222" root@172.16.12.129:/DEST  
//修改了ssh 协议的端口,默认是22

准备两台虚拟机

主机ip
r8-2192.168.134.148
c8-2-154192.168.134.154

准备工作

//关闭防火墙
[root@c8-2-154 ~]# systemctl disable firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
//关闭selinux 修改配置文件
[root@c8-2-154 ~]# setenforce 0
[root@c8-2-154 ~]# vi /etc/selinux/config 

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled      //修改
# SELINUXTYPE= can take one of these three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

rsync同步方式

//先查看rsync包有没有
[root@r8-2 ~]# which rsync
/usr/bin/which: no rsync in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)
//安装rsync命令
[root@r8-2 ~]# yum -y install rsync
[root@c8-2-154 ~]# yum -y install rsync

//同步文件
[root@r8-2 ~]# ls
anaconda-ks.cfg  lampv2.tar.gz  //将这个文件传输到另一台主机上
[root@r8-2 ~]# rsync -avz lampv2.tar.gz  root@192.168.134.154:/root/
The authenticity of host '192.168.134.154 (192.168.134.154)' can't be established.
ECDSA key fingerprint is SHA256:IQsjvY2LZAUowhVTxV7wagUBlnNcwVX1BuoqsjuOEw8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.134.154' (ECDSA) to the list of known hosts.
root@192.168.134.154's password:  //输入密码
sending incremental file list
lampv2.tar.gz

sent 759,117,232 bytes  received 35 bytes  60,729,381.36 bytes/sec
total size is 758,800,666  speedup is 1.00

//在另外一台主机上
[root@c8-2-154 ~]# ls
anaconda-ks.cfg  lampv2.tar.gz  //同步成功

rsync命令

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

eg: rsync [OPTION]… SRC DEST

//将文件anaconda-ks.cfg变为abc文件
[root@r8-2 ~]# ls
anaconda-ks.cfg  lampv2.tar.gz
[root@r8-2 ~]# rsync -avz anaconda-ks.cfg abc  

[root@r8-2 ~]# ls
abc  anaconda-ks.cfg  lampv2.tar.gz
[root@r8-2 ~]# ll      //发现除名字,权限、时间、大小一样
total 741028
-rw-------  1 root root      1086 Aug  5 23:36 abc
-rw-------. 1 root root      1086 Aug  5 23:36 anaconda-ks.cfg
-rw-r--r--  1 root root 758800666 Sep 30 16:32 lampv2.tar.gz

eg:rsync [OPTION]… SRC [USER@]HOST:DEST

//将一台主机上面的东西传到另一台主机上
[root@r8-2 ~]# rsync -avz abc root@192.168.134.154:/tmp
root@192.168.134.154's password: 
sending incremental file list
abc

sent 701 bytes  received 35 bytes  210.29 bytes/sec
total size is 1,086  speedup is 1.48
//在另一台主机上查看
[root@c8-2-154 ~]# ls /tmp/
abc    vmware-root_907-4021784429

eg:rsync [OPTION]… [USER@]HOST:SRC DEST

//在本主机上面将另一台主机上面的文件传输到本主机
[root@c8-2-154 ~]# ls /tmp/
abc    vmware-root_907-4021784429
[root@r8-2 ~]# rsync -avz root@192.168.134.154:/tmp/vmware-root_907-4021784429 .
root@192.168.134.154's password: 
receiving incremental file list
vmware-root_907-4021784429/

sent 28 bytes  received 76 bytes  41.60 bytes/sec
total size is 0  speedup is 0.00
[root@r8-2 ~]# ls
abc  anaconda-ks.cfg  lampv2.tar.gz  vmware-root_907-4021784429

常用选项:

//rsync常用选项:
    -a, --archive       //归档
    -v, --verbose       //啰嗦模式(显示整个过程)
    -q, --quiet         //静默模式
    -r, --recursive     //递归
    -p, --perms         //保持原有的权限属性
    -z, --compress      //在传输时压缩,节省带宽,加快传输速度
    --delete            //在源服务器上做的删除操作也会在目标服务器上同步

eg:–delete

//先用命令将文件传输到对端
[root@r8-2 ~]# rsync -avz lamp root@192.168.134.154:/tmp/
//将本主机上面的lamp/httpd-2.4.57/删掉          
[root@r8-2 ~]# rm -rf lamp/httpd-2.4.57/
//再次传输一遍,但是将--delete加上
[root@r8-2 ~]# rsync -avz --delete lamp root@192.168.134.154:/tmp/

//查看对端
[root@c8-2-154 lamp]# ls
apr-1.7.4  apr-util-1.6.3  files  lamp.sh  php-8.2.10
                                                        //已经删除

免密传输

[root@r8-2 ~]# ssh-keygen -t rsa   //设置免密
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gdvO4V4cI7dWiGWDm0v/0aJ9CUgdjKWWeDodQisHuNE root@r8-2
The key's randomart image is:
+---[RSA 3072]----+
|     o. .  +.    |
|    o E+ +.oo    |
|     oo B X. .   |
|    .  = &.+.    |
|      . S.*..    |
|       = O.=..   |
|        = * o... |
|       . o + oo  |
|        . . o.   |
+----[SHA256]-----+

[root@r8-2 ~]# ssh-copy-id root@192.168.134.154    //设置哪台主机免密
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.134.154's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@192.168.134.154'"
and check to make sure that only the key(s) you wanted were added.

实时同步(inotify)

rsync与传统的cptar备份方式相比,rsync具有安全性高、备份迅速、支持增量备份等优点,通过rsync可以解决对实时性要求不高的数据备份需求,例如定期的备份文件服务器数据到远端服务器,对本地磁盘定期做数据镜像等。

rsync不足:

1、rsync同步数据时,需要扫描所有文件后进行比对,进行差量传输。如果文件数量达到了百万甚至千万量级,扫描所有文件将是非常耗时的。而且正在发生变化的往往是其中很少的一部分,这是非常低效的方式。

2、rsync不能实时的去监测、同步数据,虽然它可以通过linux守护进程的方式进行触发同步,但是两次触发动作一定会有时间差,这样就导致了服务端和客户端数据可能出现不一致,无法在应用故障时完全的恢复数据。

基于以上原因,rsync+inotify组合出现了!

Inotify

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

实验:

环境说明:

源服务器类型ip应用
源服务器192.168.134.148rsync + inotify-tools脚本
目标服务器192.168.134.154rsync
在目标服务器上
//关闭防火墙 selinux
[root@c8-2-154 ~]# systemctl disable --now firewalld
[root@c8-2-154 ~]# setenforce 0
[root@c8-2-154 ~]# vim /etc/selinux/config
SELINUX=disabled  //将这一行改成关闭

//查看目标服务器有没有服务
[root@c8-2-154 ~]# rpm -qa rsync | grep '\.service'
//查看要安装的包
[root@c8-2-154 ~]# yum list all | grep rsync
rsync.x86_64   (rhel7安装这个就行)             
libguestfs-rsync.x86_64   
rsync-daemon.noarch     //守护进程(rhel8版本在目标上面要安装)    

//安装命令
[root@c8-2-154 ~]# yum -y install rsync rsync-daemon

//查看服务
[root@c8-2-154 ~]# rpm -ql rsync-daemon
/etc/rsyncd.conf
/etc/sysconfig/rsyncd
/usr/lib/systemd/system/rsyncd.service //发现服务
/usr/lib/systemd/system/rsyncd.socket
/usr/lib/systemd/system/rsyncd@.service
/usr/share/man/man5/rsyncd.conf.5.gz

//配置rsync.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

//写一个文件/etc/rsync.pass,将用户名和密码写进去
[root@c8-2-154 ~]# echo 'admin:1005' > /etc/rsync.pass
//设置文件权限
[root@c8-2-154 ~]# chmod 600 /etc/rsync.pass

//服务开机自启
[root@c8-2-154 ~]# systemctl enable --now rsyncd
Created symlink /etc/systemd/system/multi-user.target.wants/rsyncd.service → /usr/lib/systemd/system/rsyncd.service.

//查看端口号(873)
[root@c8-2-154 ~]# ss -antl
State     Recv-Q    Send-Q         Local Address:Port         Peer Address:Port    Process    
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                  [::]:*   

源服务器上
//关闭防火墙 selinux
[root@r8-2 ~]# systemctl disable --now firewalld
[root@r8-2 ~]# setenforce 0
[root@r8-2 ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/sysconfig/selinux

//安装rsync
[root@r8-2 ~]# yum -y install rsync

//创建认证密码文件
[root@r8-2 ~]# echo '1005' > /etc/rsync.pass   //将目标主机创建的密码告诉本主机
//设置权限
[root@r8-2 ~]# chmod 600 /etc/rsync.pass

//同步文件
[root@r8-2 ~]# ls abc
aa  bb  cc
[root@r8-2 ~]# rsync -avH --port 873 --progress --delete /root/abc admin@192.168.134.154::etc_from_client --password-file=/etc/rsync.pass
//去对端查看
[root@c8-2-154 tmp]# ls  abc
aa  bb  cc

//现在将abc中的aa删掉
[root@r8-2 ~]# rm -f abc/aa
//再次同步
[root@r8-2 ~]# rsync -avH --port 873 --progress --delete /root/abc admin@192.168.134.154::etc_from_client --password-file=/etc/rsync.pass
//去对端查看
[root@c8-2-154 tmp]# ls abc/
bb  cc

实时同步

//安装inotify-tools工具,实时触发rsync进行同步
//查看服务器内核是否支持inotify
[root@r8-2 ~]# ll /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 Oct  1 16:11 max_queued_events
-rw-r--r-- 1 root root 0 Oct  1 16:11 max_user_instances
-rw-r--r-- 1 root root 0 Oct  1 16:11 max_user_watches
//如果有这三个max开头的文件则表示服务器内核支持inotify

//安装一个依赖包
[root@r8-2 ~]# yum -y install epel-release
//查看
[root@r8-2 ~]# yum list all | grep inotify
python3-inotify.noarch                                            0.9.6-13.el8                                                      @anaconda         
inotify-tools.x86_64 //安装这个包                                             3.14-19.el8                                                       epel              
inotify-tools-devel.x86_64                                        3.14-19.el8                                                       epel              
python3-inotify_simple.noarch                                     1.3.4-1.el8                                                       epel              
rubygem-rb-inotify.noarch                                         0.10.0-1.el8                                                      epel              
rubygem-rb-inotify-doc.noarch                                     0.10.0-1.el8                                                      epel   
//安装包
[root@r8-2 ~]# yum -y install inotify-tools
//查看包是否存在
[root@r8-2 ~]# rpm -qa | grep inotify
python3-inotify-0.9.6-13.el8.noarch
inotify-tools-3.14-19.el8.x86_64 //发现已存在表示安装成功

//写同步脚本
//首先创建专门的目录存放脚本
[root@r8-2 ~]# mkdir /scripts
[root@r8-2 ~]# cd /scripts/
[root@r8-2 scripts]# touch /scripts/inotify.sh
[root@r8-2 scripts]# vim inotify.sh
#!/bin/bash
  
host=192.168.134.154   # 目标服务器的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 \    #-e:事件,表示监控文件属性发生改变、删除
| while read files;do   #表示前面的事件发生后,后面来处理 files:变量,代替-e后面的内容
    rsync -avzP --delete  --timeout=100 --password-file=${password} $src $user@$host::$des
    echo "${files} was rsynced" >>/tmp/rsync.log 2>&1     #把同步的文件写到日志里面去,2>&1:表示将错误的也扔进去
done

//给执行权限
[root@r8-2 scripts]# chmod +x inotify.sh

//执行脚本   nohup:可以让你在退出终端或关闭SSH连接后继续运行命令
[root@r8-2 scripts]# nohup ./inotify.sh &       //&:放后台
[1] 10930
[root@r8-2 scripts]# nohup: ignoring input and appending output to 'nohup.out'
                                          //此处会自动生成一个文件,直接回车就好
[root@r8-2 scripts]# jobs
[1]+  Running                 nohup bash inotify.sh &
[root@r8-2 scripts]# ps -ef | grep inotify
root        2229    2109  0 04:30 pts/0    00:00:00 bash inotify.sh
root        2230    2229  0 04:30 pts/0    00:00:00 /usr/bin/inotifywait -mrq --timefmt %Y%m%d %H:%M --format %T %w%f%
root        2231    2229  0 04:30 pts/0    00:00:00 bash inotify.sh
root        2244    2109  0 04:31 pts/0    00:00:00 grep --color=auto inotify

//检验:触发事件
[root@r8-2 scripts]# echo "hello world" > /etc/abc
//去对端查看
[root@c8-2-154 tmp]# ls /tmp/etc/abc
hello world

//在此时再次写入
[root@r8-2 scripts]# echo "haha" > /etc/abc
//在对端查看
[root@c8-2-154 tmp]# cat /tmp/etc/abc
haha

//删除文件
[root@r8-2 scripts]# rm -f /etc/abc
//在对端查看
[root@c8-2-154 tmp]# ls /tmp/etc/abc
ls: cannot access '/tmp/etc/abc': No such file or directory

设置脚本开机自动启动

//查看文件                              //发现文件链接到rc.d/rc.local
[root@r8-2 ~]# ll /etc/rc.local 
lrwxrwxrwx. 1 root root 13 Mar 11  2021 /etc/rc.local -> rc.d/rc.local
[root@r8-2 ~]# ll /etc/rc.d/rc.local
-rw-r--r--. 1 root root 474 Mar 11  2021 /etc/rc.d/rc.local
                                     //:/etc/rc.d/rc.local是系统启动之后要执行的文件                                                 
//给执行文件加权限
[root@r8-2 ~]# chmod +x /etc/rc.d/rc.local 
[root@r8-2 ~]# vim /etc/rc.d/rc.local
#!/bin/bash  //在第一行后面加
nohup /scripts/inotify.sh &

//验证:
[root@r8-2 ~]# echo "haha" > /etc/aa
//在对端查看
[root@c8-2-154 etc]# cat /tmp/etc/aa
haha

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值