rsync和inotify-tools,Rsync+inotify与rsync+sersync的区别

https://github.com/wsgzao/sersync

一.常见的远程数据同步工具

  1. Scp
    pLinux系统自带的远程同步数据命令
    不支持时时数据同步
  2. Rsyunc.
    数据同步服务
    支持使用脚本或者动态时时数据同步
  3. Sftpe
    使用stp协议数据上传或者下载
    2,安装rsync和rsync常见命令选项
    1)安装rsync
  • 发起端和备份源

        发起端:负责发起rsync同步操作的客户机叫做发起端,通知服务端我要备份你的数据
        备份端:负责相应来自客户机rsync同步操作的服务器所在的备份源,需要备份的服务器。
        服务端:运行rsyncd服务,需要备份的服务器。
        客户端:存放备份数据

数据同步方式

        推push : 主机负责把数据传送给其他主机,服务器开销很大,比较适合后端服务器少的情况
        拉pull:所有主机定时去找一主机拉数据,可能就会导致数据缓慢。
        推:目的主机配为rsyng服务器,源主机周期性的使用rsync命令把要同步的目录推过去
        拉:源主机配置为rsync服务器,目的E机周期性的使用rsync命令把要同步的目录拉过来
        两种方案,rsync都有对应的命令来实现

rsync远程同步方法
方法一(ssh链接同步):
ssh连接远程服务器,对对方电脑进行操控监听服务器仅需要安装ssh(scp)服务,并非必须安装rsync

方法一(模组同步):
模组同步需要监听服务器安装Rsync并运行rsync进程,默认监听端口为873,数据不经过加密传输。

  1. 通过ssh将服务器A的文件同步到监听服务器的指定目录下
  • 端在服务段发起同步,也就是服务端同步到客户端,在172.16.10.1 rsync的服务端也就是数据源
    [root@harbor opt]# rsync -av -e "ssh -p 22" /opt/test  root@172.16.10.4:/opt/laomu

  • 检查客户端是不存在
    [root@localhost laomu]# ls -al
    总用量 0
    drwxr-xr-x   3 root root  18 7月  15 10:52 .
    drwxr-xr-x. 13 root root 200 7月  15 10:52 ..
    drwxr-xr-x   5 root root 194 7月  15 10:33 test

    2.通过模组进行传输,

  • 在客户端查看服务端模【service】组信息
[root@localhost laomu]# rsync 172.16.10.1::service
drwxr-xr-x            194 2022/07/15 10:33:37 .
-rw-r--r--              0 2022/07/15 10:04:35 a
-rw-r--r--         51,917 2022/07/15 09:52:07 inotify-tools-3.14-9.el7.x86_64.rpm
-rw-r--r--              6 2022/07/15 10:02:48 l
-rwxr-xr-x            247 2022/07/15 10:02:12 rsync.sh
-rw-r--r--        727,290 2022/07/15 10:33:19 sersync2.5.4_64bit_binary_stable_final.tar.gz
-rw-r--r--              6 2022/07/15 08:46:47 test1
drwxr-xr-x             41 2011/10/26 14:19:35 GNU-Linux-x86
drwxr-xr-x             18 2022/07/15 09:49:26 wubo
drwxr-xr-x             19 2022/07/15 09:55:31 wuqi
  • 在客户端拉去服务端内容到客户端
    [root@localhost laomu]# rsync -avz --delete root@172.16.10.1::service --password-file=/etc/rsync.password /opt/test 

rsync远程同步

  • 技能展示
  1. 会配置rsync备份源
  2. 会使用rsync下行,上行异地备份
  3. 会使用inotify+rsync实时备份
  • rsync 简介

  Rsync(remote synchronize)是一个远程数据同步工具,可通过LAN/WAN快速同步多台主机间的文件,也可以使用 Rsync 同步本地硬盘中的不同目录。 
  Rsync 是用于取代rcp的一个工具,Rsync使用所谓的 “Rsync 算法” 来使本地和远程两个主机之间的文件达到同步,这个算法只传送两个文件的不同部分,而不是每次都整份传送,因此速度相当快。您可以参考 How Rsync Works A Practical Overview 进一步了解 rsync 的运作机制。
  Rsync支持大多数的类Unix系统,无论是Linux、Solaris还是BSD上都经过了良好的测试。此外,它在windows平台下也有相应的版本,比较知名的有cwRsync和Sync2NAS。
  Rsync 的初始作者是 Andrew Tridgell 和 Paul Mackerras,它当前由 http://rsync.samba.org维护。
  Rsync的基本特点如下:
  1. 可以镜像保存整个目录树和文件系统;
  2. 可以很容易做到保持原来文件的权限、时间、软硬链接等;
  3. 无须特殊权限即可安装;
  4. 优化的流程,文件传输效率高;
  5. 可以使用rcp、ssh等方式来传输文件,当然也可以通过直接的socket连接;
  6. 支持匿名传输,以方便进行网站镜像。
  在使用 rsync 进行远程同步时,可以使用两种方式:远程 Shell 方式(建议使用 ssh,用户验证由 ssh 负责)和 C/S 方式(即客户连接远程 rsync 服务器,用户验证由 rsync 服务器负责)。
  无论本地同步目录还是远程同步数据,首次运行时将会把全部文件拷贝一次,以后再运行时将只拷贝有变化的文件(对于新文件)或文件的变化部分(对于原有文件)。
  rsync 在首次复制时没有速度优势,速度不如 tar,因此当数据量很大时您可以考虑先使用 tar 进行首次复制,然后再使用 rsync 进行数据同步。

  • 重点
  1. 配置rsync源服务器
  2. rsync上下行远程同步

配置rsync源服务器

       rsync (Remote Sync,远程同步)是一个开源的快速备份工具,可以在不同主机之间镜像同步整个目录树,支持增量备份,保持链接和权限,且采用优化的同步算法,传输前执行压缩,因此非常·适用于异地备份、镜像服务器等应用.
rsync的官方站点是htp://rsync. sarba,org/.目前最新版本是3.1.2.,由Wayne Davison进行维护。作为一种最常用的文件备份工具, rsync往往是Linux和UNIX系统默认安装的基本组件之一。

       在远程同步任务中,负责发起rsync同步操作的客户机称为发起端,而负责响应来自客户机的rsync同步操作的服务器称为同步源,在同步过程中,同步源负责提供文档的原始位置,发起端应对该位置具有读取权限.
下面介绍如何配置rsync同步源
      rsync作为同步源时以守护进程运行,为其他客户机提供备份源,配置rsymc同步源需要建立配置文件rsynod. cont,创建备份账号,然后将rsync程序以守护进程(’–daemon"选项)方式运行。

、系统环境

rsync 服务器:172.16.10.1
rsync 客户端:172.16.10.4

系统平台:CentOS 7.x

如图所示,搭建网络,配置地址。

1.在172.16.10.1服务器上配置为服务端,修改rsync的配置文件/etc/rsyncd.conf,并启动rsync服务程序。

2.在172.16.10.4上使用rsync命令验证是否能够从服务端(/opt/wubo)下载文件到客户机端(/opt/wubo)。

3.修改rsync的配置文件/etc/rsyncd.conf,实现客户机端(/opt/wubo)能上传文件到服务端的(/opt/wubo)位置。在客户机端验证。

4.在172.16.10.1上实现每天晚上22:00对服务器的网站目录(/opt/wubo)做一次同步

 三、服务器端与客户端安装rsync服务并运行 

 #检查rsync软件是否存在
[root@harbor ~]# rpm -qa | grep rsync
rsync-3.1.2-4.el7.x86_64
#安装rsync服务
[root@harbor ~]# yum install rsync
#启动rsync服务
[root@harbor ~]# systemctl enable rsyncd.service --now
#检查是否已经成功启动
[root@harbor ~]# netstat -lnp|grep 873
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      764/rsync           
tcp6       0      0 :::873                  :::*                    LISTEN      764/rsync           
unix  2      [ ACC ]     STREAM     LISTENING     1737597  357/containerd-shim  /run/containerd/s/e03b9a5d2360908d6e0d45c3858b52febf49fcd40b789432f8731c29c275ae94
[root@harbor ~]#

四、rsync服务工作方式(3种)

1.实现本地数据传输备份 

本地
[root@harbor opt]# rsync -avz /opt/test /opt/test1

传输远程
[root@harbor test]# rsync -a /opt/test 172.16.10.4:~

2.实现ssh远程数据传输备份

[root@harbor test]# rsync -avz -e "ssh -p22"  /opt/test 172.16.10.4:/opt

 3.实现socket守护进程数据传输

[root@harbor opt]# rsync -avz /opt/test rsync_backup@172.16.10.1::backup

五、服务端配置

1.配置rsync软件文件(/etc/rsyncd.conf)

[root@harbor ~]# cat /etc/rsyncd.conf 
# /etc/rsyncd: configuration file for rsync daemon mode

# See rsyncd.conf man page for more options.

# configuration example:

# uid = nobody
# gid = nobody
# use chroot = yes
# max connections = 4
# pid file = /var/run/rsyncd.pid
# exclude = lost+found/
# transfer logging = yes
# timeout = 900
# ignore nonreadable = yes
# dont compress   = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2


uid                 = root
gid                 = root
use chroot          = no
max connections     = 200
timeout             = 3000
address             = 172.16.10.1
port                = 873
lock file           = /var/run/rsyncd.lock
log file            = /var/log/rsyncd.log
pid file            = /var/run/rsyncd.pid
exclude             = lost+found/
transfer logging    = yes
log format          = %t %a %m %f %b
ignore errors       = yes
ignore nonreadable  = yes
dont compress       = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2

[service]
        comment         = this is jettech server
        path            = /opt/test
        read  only      = no
        write only      =no
        list            = list
        munge symlinks  = no
        ignore errors   = yes
        auth user       = root
        secrets file    = /etc/rsyncd.pass
        hosts allow     = *
        hosts deny      = 0.0.0.0/32 

    参数解释

#rsync_config
#created by HQ at 2017
##rsyncd.conf start##
uid = rsync --- 虚拟用户rsync,管理备份目录 原理???
gid = rsync --- 虚拟用户组rsync,管理备份目录
port = 873 --- 服务默认端口号873
fake super = yes --- 伪装管理员功能开启 便于可以执行chgrp命令
use chroot = no --- 安全配置 !!!
max connections = 200 --- 最大连接数 同时支持200个客户端连接
timeout = 300 --- 连接超时时间 秒
pid file = /var/run/rsyncd.pid --- 进程信息文件 
便于获取进程号停止进程
便于判断服务是否启动 避免反复启动
lock file = /var/run/rsync.lock --- 锁文件
log file = /var/log/rsyncd.log --- 服务运行时日志文件
ignore errors --- 忽略传输过程一些小错误
read only = false --- 指定备份目录的权限为可读可写 
list = false --- ???
hosts allow = 172.16.1.0/24 --- 安全策略配置 设置一个白名单
hosts deny = 0.0.0.0/32 --- 安全策略配置 设置一个黑名单
auth users = rsync_backup --- 定义认证用户
secrets file = /etc/rsync.password --- 密码文件 用户密码信息 rsync_backup:oldboy123
[backup] --- 模块 名称
comment = "backup dir by oldboy"
path = /backup --- 定义一个备份目录

配置二详解

###全局配置
address = 172.16.10.1			#指定服务器IP地址
port = 873			#指定运行端口,默认是873,您可以自己指定;
uid = root			#rsync使用的用户,默认nobody
gid = root			#rsync使用的gid 默认nobody
#注:服务器端传输文件时,要发哪个用户和用户组来执行,默认是nobody。 如果用nobody 用户和用户组,可能遇到权限问题,有些
#文件从服务器上拉不下来。所以我就偷懒,为了方便,用了root 。不过您可以在定义要同步的目录时定义的模块中指定用户来解决权限的问题。
use chroot = no		#是否限定在该目录下,默认为true
#当有软连接时,需要改为fasle,如果为true就限定为模块默认目录,通常都在内网使用rsync所以不配也可以
pid file = /var/run/rsyncd.pid    	#pid文件位置
lock file = /var/run/rsync.lock  	#指定lock文件用来支持"max connections"参数使总连接不会超过限制
log file = /var/log/rsyncd.log 		#日志文件路径
max connections = 200			#设置最大连接数,默认0,意思无限制,负值为关闭这个模块
timeout = 300			#默认为0,表示no timeout,建议300-600(5-10分钟)
transfer logging = yes			#使rsync服务器使用ftp格式的文件来记录下载和上载操作在自己单独的日志中。
log format = %t %a %m %f %b			#通过该选项用户在使用transfer logging可以自己定制日志文件的字段。其格式是
#一个包含格式定义符的字符串,可以使用的格式定义符如下所示:
#%h 远程主机名
#%a 远程IP地址
#%l 文件长度字符数
#%p 该次rsync会话的进程id
#%o 操作类型:"send"或"recv"
#%f 文件名
#%P 模块路径
#%m 模块名
#%t 当前时间
#%u 认证的用户名(匿名时是null)
#%b 实际传输的字节数
#%c 当发送文件时,该字段记录该文件的校验码
#默认log格式为:"%o %h [%a] %m (%u) %f %l",一般来说,在每行的头上会添加"%t [%p] "。在源代码中同时发布有一个叫
#rsyncstats的perl脚本程序来统计这种格式的日志文件。

ignore nonreadable = yes			#指定rysnc服务器完全忽略那些用户没有访问权限的文件。这对于在需要备份的目录
									#中有些文件是不应该被备份者得到的情况是有意义的。		

dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2			#用来指定那些不进行压缩处理再传输的文件,
															#默认值是*.gz *.tgz *.zip *.z *.rpm *.deb *.iso *.bz2 *.tbz。

###目录配置
[rsync]
	comment= "测试"
	path = /data/rsync
	ignore errors = yes			#是否忽略IO错误
	read only = no			#read only 是只读选择,也就是说,不让客户端上传文件到服务器上
	write only = no			#write only指只可以上传文件不可以下载
	hosts allow = 192.168.3.55			#可以指定单个IP,也可以指定整个网段,能提高安全性。格式是ip 与ip 之间、
										#ip和网段之间、网段和网段之间要用空格隔开;
	hosts deny = *
	list = yes			# #list 意思是把rsync 服务器上提供同步数据的目录在服务器上模块是否显示列出来。默认是yes。
						#如果你不想列出来,就no ;如果是no是比较安全的,至少别人不知道你的服务器上提供了哪些目录。
	exclude = file1/ file2/			#exclude是排除的意思,也就是说,要把/data/rsync目录下的file1和
										#file2排除在外; beinan/和samba/目录之间有空格分开
	auth user = tytt			#该选项指定由空格或逗号分隔的用户名列表,只有这些用户才允许连接该模块。这里的用户
								#和系统用户没有任何关系。如果"auth users"被设置,那么客户端发出对该模块的连接
								#请求以后会被rsync请求challenged进行验证身份,这里使用的challenge/response
								#认证协议。用户的名和密码以明文方式存放在"secrets file"选项指定的文件中。
								#默认情况下无需密码就可以连接模块(也就是匿名方式)。
	secrets file = /etc/rsync.passwd			#该选项指定一个包含定义用户名:密码对的文件。只有在"auth users"
												#被定义时,该文件才有作用。文件每行包含一个username:passwd对。
												#一般来说密码最好不要超过8个字符。没有默认的secures file名,
												#需要限式指定一个。(例如:/etc/rsyncd.secrets)

2.创建备份目录管理用户

useradd -s /sbin/nologin -M rsync 创建程序(虚拟)用户

id rsync 查看用户信息

3.创建认证用户密码文件

#设置用户密码文件
echo "root:123456aA" > /etc/rsyncd.pass 

 #设置配置文件权限为只读
chomd 600 /etc/rsyncd.pass

 4.创建备份目录

mkdir /opt/test

#将所创目录属组设为认证用户
chown -R root.root /opt/test 

5 启动服务 

[root@harbor opt]# systemctl restart rsyncd
[root@harbor opt]# systemctl status rsyncd
● rsyncd.service - fast remote file copy program daemon
   Loaded: loaded (/usr/lib/systemd/system/rsyncd.service; enabled; vendor preset: disabled)
   Active: active (running) since 五 2022-07-15 09:31:31 CST; 3s ago
 Main PID: 26914 (rsync)
    Tasks: 1
   Memory: 244.0K
   CGroup: /system.slice/rsyncd.service
           └─26914 /usr/bin/rsync --daemon --no-detach

7月 15 09:31:31 harbor.cclinux.cn systemd[1]: Started fast remote file copy program daemon.

6.客户端验证 在172.16.10.4上面操作

[root@localhost opt]# rsync -avz root@172.16.10.1::service /opt/test 
receiving incremental file list
created directory /opt/test
./
test1

sent 50 bytes  received 129 bytes  358.00 bytes/sec
total size is 6  speedup is 0.03
[root@localhost opt]# ls /opt/test/
test1

六、客户端部署免密钥传输数据流程(–password-file) 

[root@localhost opt]# echo 123456aA >>/etc/rsync.password
[root@localhost opt]# chmod 600 /etc/rsync.password 

[root@localhost opt]# rsync -avz root@172.16.10.1::service --password-file=/etc/rsync.password /opt/test 
receiving incremental file list

sent 24 bytes  received 72 bytes  192.00 bytes/sec
total size is 6  speedup is 0.06

.rsync参数选项

[root@localhost opt]# rsync -avz root@172.16.10.1:: list
service        	this is test
1.-avz

-v 表示:显示详细信息
-z 表示:传输是进行压缩提高传输效率
-a(rtpP) 表示:递归传输数据,保持文件属性

2.-rp
-r 表示:表递归传输
-p 表示:保持权限不变

3.-t
-t 表示:保持时间信息

4.-P
-P 表示:显示同步过程及传输进度信息

5.-e
-e 表示:信道协议-----ssh
例:
rsync -avz -e  "ssh -p22" /opt/test root@172.16.10.1:/backup
ssh远程登录传输数据**

6.–delete **
–delete 表示:无差异同步数据(本地和rsync服务端数据同步)
例:rsync --delete -avz /opt/test root@172.16.10.1:/backup --password-file=/etc/rsync.password

7.–exclude
–exclude 参数指定排除的文件或目录信息
例:rsync -avz /opt/test  --exclude=a --exclude=b --exclude=d/2 root@172.16.10.1:/backup –password-file=/etc/rsync.password

8.–exclude-from
–exclude-from 参数指定排除多个数据信息文件
例:rsync -avz /opt/test  --exclude-from=/opt/test/**exclude.txt **  root@172.16.10.1:/backup –password-file=/etc/rsync.password

同步源数据删除目标目录数据 

[root@localhost test]# rsync -avz --delete root@172.16.10.1::service --password-file=/etc/rsync.password /opt/test 

八、部分补充说明

1.对备份目录进行分别授权

chown -R rsync.rsync /opt/test -R sa.sa /opt/test
chown -R dev.dev /devbackup/

重启服务

killall rsync && rsync --daemon

2.黑白名单访问策略

(1)只有白名单,没有黑名单,只按白名单执行,默认规则是阻止
(2)没有白名单,只有黑名单,按黑名单执行,默认规则是允许
(3)默认规则允许,白名单优于黑名单

3.守护进程无差异同步配置

–delete 实现无差异同步数据传输

4.守护进程列表功能配置(list= )
list=true(可以让rsync客户查看到rsync服务端所有的模块信息)
list=false(不可以让rsync客户查看到rsync服务端所有的模块信息)

查看命令:rsync  root@172.16.10.1::
建议为false,安全

九.rsync实时数据同步

  1. 定期同步数据
    通过计划任务执行脚本定时同步数据
    同步数据速度慢
    同步延迟大
  2. 实时同步数据
    根据同步源状态实时同步数据
    源发生改变自动触发更新
    延迟小同步速度快
    安装inotify
    # 先安装扩展包源,否则inotify-tools找不到
    yum install epel-release
    yum install inotify-tools 
    
    [root@harbor test]# yum localinstall install inotify-tools-3.14-9.el7.x86_64.rpm 
  3. Inotifywait
    持久化监控使用 
  4. Inotifywatch
    临时监控数据使, inotifywatch监控选项和事件类型
  5. 常见的选项
    -e:指定监控事件
    -r:目录循环监控
    -m:持续监控
  6. 监控数据类型
    create:创建
    delete:删除
    move:剪切
    modify:修改数据
    attirb:修改属性
  7. 动态监控bdqn目录变化,在172.16.10.1 rsync服务端 监听。然后在开启一个窗口随便创建文件 这里就有有变化
    [root@harbor test]# inotifywait -mrq -e move,delete,create,modify,attrib /opt/test/
    /opt/test/ CREATE,ISDIR wuqi
    /opt/test/wuqi/ CREATE aaaaa
    /opt/test/wuqi/ MODIFY aaaaa
  8. .配置脚本实时同步数据,先来看下服务器内核是否支持inotify,我用的centos7默认是支持的,如果不支持需要安装配置

    [root@harbor opt]# ls -l /proc/sys/fs/inotify ##列出文件目录,出现下面的内容,说明服务器内核支持inotify
    总用量 0
    -rw-r--r-- 1 root root 0 7月  15 10:07 max_queued_events
    -rw-r--r-- 1 root root 0 7月  15 10:07 max_user_instances
    -rw-r--r-- 1 root root 0 7月  15 10:07 max_user_watches
    
    
    
    在/proc/sys/fs/inotify目录下的三个文件,对inotify机制有一定的限制
    max_user_watches:设置inotifywait或inotifywatch命令可以监视的文件数量(单进程)
    max_user_instances:设置每个用户可以运行的inotifywait或inotifywatch命令的进程数。
    max_queued_events:设置inotify实例事件(event)队列可容纳的事件数量。
    
    
    
    
    
     注意:inotify默认内核参数值有点小,可以对inotify默认参数进行修改,
    [root@harbor test]# cat /etc/sysctl.conf 
    # sysctl settings are defined through files in
    # /usr/lib/sysctl.d/, /run/sysctl.d/, and /etc/sysctl.d/.
    #
    # Vendors settings live in /usr/lib/sysctl.d/.
    # To override a whole file, create a new file with the same in
    # /etc/sysctl.d/ and put new settings there. To override
    # only specific settings, add a file with a lexically later
    # name in /etc/sysctl.d/ and put new settings there.
    #
    # For more information, see sysctl.conf(5) and sysctl.d(5).
    net.ipv4.ip_forward=1
    vm.max_map_count = 262144
    fs.inotify.max_queued_events = 16387
    fs.inotify.max_user_instances = 2048
    fs.inotify.max_user_watches   = 1048576

    介绍使用:

    [root@harbor wuqi]# ls
    demo1.sh  srcdir
    [root@harbor wuqi]# cat demo1.sh 
    #!/bin/bash
    
    srcdir=/opt/wuqi/srcdir
    inotifywait -rq --timefmt '%d/%m/%y-%H:%M' --format '%T %w%f' -e modify,create,attrib ${srcdir} \
    | while read file
    do
      echo "${file} is notified!"
    done

    -m 持续监听
    -r 使用递归形式监视目录
    -q 减少冗余信息,只打印出需要的信息
    -e 指定要监视的事件,多个时间使用逗号隔开
    –timefmt 时间格式
    –format 监听到的文件变化的信息

    ymd分别表示年月日,H表示小时,M表示分钟
    –format 说明:
    %w 表示发生事件的目录
    %f 表示发生事件的文件
    %e 表示发生的事件
    %Xe 事件以“X”分隔
    %T 使用由–timefmt定义的时间格式


    运行demo1.sh这后,在srcdir目录中任意创建一个文件,就输入程序中定义的信息

    [root@harbor wuqi]# ./demo1.sh 
    15/07/22-10:13 /opt/wuqi/srcdir/a is notified!

    测试二(获取文件名)

    [root@harbor wuqi]# cat file.sh 
    #!/bin/bash
    
    srcdir=/opt/wuqi/srcdir
    inotifywait -mrq --timefmt '%d/%m/%y-%H:%M' --format '%T %w%f' -e create ${srcdir} \
    | while read file
    do
      echo "${file} is notified!"
      NEWFILE=`echo ${file} | cut -d ' ' -f 2`
      echo "${NEWFILE}"
    done

    在–format参数中%T后面有一个空格,所以时间和文件名就以空格拆分

    [root@harbor wuqi]# ./file.sh 
    15/07/22-10:14 /opt/wuqi/srcdir/wuqi is notified!
    /opt/wuqi/srcdir/wuqi

    加入开机启动

    demo3.sh为例

    # chmod +x rc.local
    
    
    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.
     
    touch /var/lock/subsys/local
     
    nohup /opt/wuqi/demo3.sh >> /var/log/inotify_flume.log &
    

    源文件定时压缩备份

    [root@manager cronbak]# vim /etc/crontab 
    
    SHELL=/bin/bash
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    MAILTO=root
    
    # For details see man 4 crontabs
    
    # Example of job definition:
    # .---------------- minute (0 - 59)
    # |  .------------- hour (0 - 23)
    # |  |  .---------- day of month (1 - 31)
    # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
    # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
    # |  |  |  |  |
    # *  *  *  *  * user-name  command to be executed
    # 每隔1分钟执行下边的命令,测试
    */1 * * * *  root  /opt/wuqi/cron_bak.sh
    
    /opt/wuqi/cron_bak.sh
    #!/bin/bash
    
    srcdir="/opt/wuqi"
    destinatedir="/opt/wuqi_back"
    flumedatadir="/opt/wubo/meteorological_data"
    # nowdate=$(date "+%Y-%m-%d %H:%M:%S")
    nowdate=$(date -d "-1 days" +"%Y-%m-%d")
    # nowdate=$(date -d "-1 days 2022-07-07" +"%Y-%m-%d")
    # startdate="$nowdate 00:00:00"
    enddate="$nowdate 21:59:59"
    echo "$nowdate"
    echo "$startdate"
    echo "$enddate"
    
    for dir in `ls $srcdir`
    do
      subsrcdir="$srcdir/$dir"
      subdesdir="$destinatedir/$dir"
      if [ -d "$subsrcdir" ];then
        # check destinate dictionary
        [ ! -d "$subdesdir" ] && mkdir $subdesdir
        # bake file here
        daydocument="$subdesdir/${dir}_$nowdate"
        [ ! -d "$daydocument" ] && mkdir $daydocument
        # bake data here
        echo "begin to move data file to $daydocument which create time lower than $enddate"
        find $subsrcdir -maxdepth 2 -type f -name '*.dat' -not -newermt "$enddate" -exec mv {} $daydocument \;
        echo "move successfully for date $nowdate"
      else
        echo "$srcdir/${dir} is not a dectionary so skipped..."
      fi
    done
    
    for file in `ls $flumedatadir`
    do
      echo "begin to delete *.COMPLETED which create time lower than $enddate"
      find $flumedatadir -maxdepth 2 -type f -name '*.COMPLETED' -not -newermt "$enddate" -exec rm {} \;
      echo "delete successfully for date $nowdate"
    done
    


    一。rsync+sersync简述
    1.sersync是基于Inotify开发的,类似于Inotify-tools的工具
    2.sersync可以记录下被监听目录中发生变化的(包括增加、删除、修改)具体某一个文件或某一个目录的名字,然后使用rsync同步的时候,只同步发生变化的这个文件或者这个目录。


    二 Rsync+Inotify-tools与Rsync+sersync这两种架构有什么区别?
    1.rsync+inotify-tools
         Inotify-tools只能记录下被监听的目录发生了变化(包括增加、删除、修改),并没有把具体是哪个文件或者哪个目录发生了变化记录下来;

         rsync在同步的时候,并不知道具体是哪个文件或者哪个目录发生了变化,每次都是对整个目录进行同步,当数据量很大时,整个目录同步非常耗时(rsync要对整个目录遍历查找对比文件),因此,效率很低。

    2. rsync+sersync
        sersync可以记录下被监听目录中发生变化的(包括增加、删除、修改)具体某一个文件或某一个目录的名字;


        rsync在同步的时候,只同步发生变化的这个文件或者这个目录(每次发生变化的数据相对整个同步目录数据来说是很小的,rsync在遍历查找比对文件时,速度很快),因此,效率很高。
    总结:当同步的目录数据量不大时,中小型公司建议使用Rsync+Inotify-tools;当数据量很大(几百G甚至1T以上)、文件很多时,建议使用Rsync+sersync。

  9. 编写脚本
    [root@harbor test]# cat rsync.sh 
    #!/bin/bash
    INW="inotifywait -mrq -e move,delete,create,modify,attrib /opt/test/"
    RSY="rsync -avz --delete root@172.16.10.1::service --password-file=/etc/rsync.password /opt/test1"
    $INW | while read DIRECTORY EVENT FIFE;do
    $RSY & > /dev/null
    done

  10. 后台执行
    [root@harbor test]# ./rsync.sh &
  11. 测试,随便生成修改或生成文件,就会自动同步

    [root@harbor test]# touch a
    [root@harbor test]# receiving incremental file list
    receiving incremental file list
    created directory /opt/test1
    rsync: mkdir "/opt/test1" failed: File exists (17)
    rsync error: error in file IO (code 11) at main.c(657) [Receiver=3.1.2]
    ./
    a
    inotify-tools-3.14-9.el7.x86_64.rpm
    l
    rsync.sh
    test1
    wubo/
    wubo/wubo
    wuqi/
    wuqi/aaaaa
    
    sent 180 bytes  received 48,477 bytes  97,314.00 bytes/sec
    total size is 52,186  speedup is 1.07
    [root@harbor opt]# ls
    apache-tomcat-8.5.38  apache-tomcat-8.5.38.tar.gz  containerd  logs  test  test1 

十:  安装sersync,https://github.com/wsgzao/sersync

  • 下载
[root@harbor test]# wget https://raw.githubusercontent.com/wsgzao/sersync/master/sersync2.5.4_64bit_binary_stable_final.tar.gz
  • 解压sersync,移动sersync,改名sersync
[root@harbor test]# tar -xf sersync2.5.4_64bit_binary_stable_final.tar.gz 
[root@harbor test]# cp -a GNU-Linux-x86 /usr/local/sersync
[root@harbor test]# mv /usr/local/sersync/sersync2  /usr/local/sersync/sersync
  • 设置PATH变量
[root@harbor test]# echo 'PATH=/usr/local/sersync:$PATH' > /etc/profile.d/sersync.sh
[root@harbor test]# cat /etc/profile.d/sersync.sh 
PATH=/usr/local/sersync:$PATH
[root@harbor test]# source /etc/profile.d/sersync.sh
  • 修改sersync配置文件
root@harbor test]# cat /usr/local/sersync/confxml.xml 
<?xml version="1.0" encoding="ISO-8859-1"?>
<head version="2.5">
    <host hostip="localhost" port="8008"></host>
    <debug start="false"/>
    <fileSystem xfs="false"/>
    <filter start="false">
	<exclude expression="(.*)\.svn"></exclude>
	<exclude expression="(.*)\.gz"></exclude>
	<exclude expression="^info/*"></exclude>
	<exclude expression="^static/*"></exclude>
    </filter>
    <inotify>
	<delete start="true"/>
	<createFolder start="true"/>
	<createFile start="false"/>
	<closeWrite start="true"/>
	<moveFrom start="true"/>
	<moveTo start="true"/>
	<attrib start="false"/>
	<modify start="false"/>
    </inotify>

    <sersync>

    <!--需要监控的目录-->
	<localpath watch="/opt/test">
        <!--backup远程备份主机地址 和模块备份目录-->
	    <remote ip="172.16.10.1" name="service"/>
	    <!--<remote ip="192.168.8.39" name="tongbu"/>-->
	    <!--<remote ip="192.168.8.40" name="tongbu"/>-->
	</localpath>
	<rsync>
        <!--rsync服务的参数-->
	    <commonParams params="-artuz"/>
        <!--true为服务开启 users为rsync远程服务的用户名 passwordfile为本地创建的rsync服务的密码文件-->
	    <auth start="true" users="root" passwordfile="/etc/rsync.password"/>
	    <userDefinedPort start="false" port="874"/><!-- port=874 -->
	    <timeout start="false" time="100"/><!-- timeout=100 -->
	    <ssh start="false"/>
	</rsync>
	<failLog path="/tmp/rsync_fail_log.sh" timeToExecute="60"/><!--default every 60mins execute once-->
    #设置start为true,每隔600分钟执行一次全盘同步
	<crontab start="false" schedule="600"><!--600mins--> 
	    <crontabfilter start="false">
		<exclude expression="*.php"></exclude>
		<exclude expression="info/*"></exclude>
	    </crontabfilter>
	</crontab>
	<plugin start="false" name="command"/>
    </sersync>

    <plugin name="command">
	<param prefix="/bin/sh" suffix="" ignoreError="true"/>	<!--prefix /opt/tongbu/mmm.sh suffix-->
	<filter start="false">
	    <include expression="(.*)\.php"/>
	    <include expression="(.*)\.sh"/>
	</filter>
    </plugin>

    <plugin name="socket">
	<localpath watch="/opt/tongbu">
	    <deshost ip="192.168.138.20" port="8009"/>
	</localpath>
    </plugin>
    <plugin name="refreshCDN">
	<localpath watch="/data0/htdocs/cms.xoyo.com/site/">
	    <cdninfo domainname="ccms.chinacache.com" port="80" username="xxxx" passwd="xxxx"/>
	    <sendurl base="http://pic.xoyo.com/cms"/>
	    <regexurl regex="false" match="cms.xoyo.com/site([/a-zA-Z0-9]*).xoyo.com/images"/>
	</localpath>
    </plugin>
</head>

以后台方式执行同步

[root@harbor test]# sersync -dro /usr/local/sersync/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:  /usr/local/sersync/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	root
passwordfile is 	/etc/rsync.password
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 /opt/test && rsync -artuz -R --delete ./ root@172.16.10.1::service --password-file=/etc/rsync.password >/dev/null 2>&1 
run the sersync: 
watch path is: /opt/test
[root@harbor test]# ps -ef |grep sersync 
root     28293     1  0 11:10 ?        00:00:00 sersync -dro /usr/local/sersync/confxml.xml

观察过程  发现不符合我要求呀,sersync我和rsync部署在一台服务器,来监视目录变化,然后同步到客户端去,但是看下面这个自己同步自己呀。看来sersync和rsync服务端要分开。sersync上面放原数据,rsync上面才是备份后的数据

cd /opt/test && rsync -artuz -R --delete ./ root@172.16.10.1::service --password-file=/etc/rsync.password >/dev/null 2>&1 
[root@localhost sersync]# vi /home/crontab/check_sersync.sh #编辑,代码在下文
[root@localhost sersync]# chmod +x /home/crontab/check_sersync.sh  #修改文件权限
[root@localhost sersync]# vi /etc/crontab #添加定时任务,添加内容*/10 * * * * root /home/crontab/check_sersync.sh > /dev/null 2>&1
[root@localhost sersync]# service crond reload #重新加载服务

check_sersync.sh内容 


#!/bin/sh
sersync="/usr/local/sersync/sersync2"
confxml="/usr/local/sersync/confxml.xml"
status=$(ps aux |grep 'sersync2'|grep -v 'grep'|wc -l)
if [ $status -eq 0 ];
then
$sersync -d -r -o $confxml &
else
exit 0;
fi

在CentOS中实现rsync远程同步_如水晶般澄清的双眸的博客-CSDN博客

Rsync+inotify与rsync+sersync的区别 - 技术备忘录

Crontab设置定时任务,实现rsync的自动同步 - 技术备忘录

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值