sincronización remota rsync y servidor de origen rsync + herramienta de monitoreo inotify para lograr la sincronización en tiempo real

Uno, introducción a rsync

Remote Sync, sincronización remota, es una herramienta de copia de seguridad incremental rápida de código abierto que puede reflejar y sincronizar todo el árbol de directorios entre diferentes hosts.
Admite copias de seguridad incrementales, mantiene conexiones y permisos, y utiliza algoritmos de sincronización optimizados para realizar la compresión antes de la transmisión, por lo que es muy adecuado para aplicaciones como copias de seguridad remotas y servidores espejo.
Admite replicación local o sincroniza
rsync y scp FTP con otros hosts SSH y rsync . La ventaja del mecanismo de copia de seguridad de la herramienta es que la copia de seguridad síncrona de rsync primero compara los datos modificados en la copia, lo que ahorra recursos. Si 1T de datos tiene solo 1K de cambios de datos, rsync básicamente solo necesita sincronizar 1k de datos mientras que scp es un Copia tonta, todas las copias.

1.1, modo de servicio rsync

1. Sincronizar por ssh

2. Modo C / S, rsync tiene un módulo demonio del lado del servidor y un cliente rsync

1.2, el principio del servicio rsync

En la tarea de sincronización remota, el cliente responsable de iniciar la operación de sincronización rsync se denomina iniciador y el servidor responsable de la operación de sincronización rsync correspondiente desde el cliente se denomina fuente de sincronización.
Durante el proceso de sincronización, la fuente de sincronización es responsable de proporcionar la ubicación original del documento, y el iniciador debe tener permiso de lectura para esta ubicación.
Como se muestra abajo:
Inserte la descripción de la imagen aquí

rsync es una herramienta de copia de seguridad incremental rápida que admite:
(1) replicación local;
(2) sincronización con otro SSH;
(3) sincronización con el host rsync.

Más adelante, demostraré cómo utilizar la herramienta de copia de seguridad rsync desde estos tres aspectos.

1.3 operaciones comunes de rsync

Inserte la descripción de la imagen aquí

1.4, la idea de configurar la fuente rsync

La configuración del servidor de origen rsync se divide aproximadamente en tres pasos:
(1) Establecer un archivo de configuración rsync;
(2) Crear un archivo de datos para la cuenta de respaldo;
(3) Iniciar el servicio rsync.

Dos, construir el servicio rsync

Prepare dos máquinas virtuales, una como fuente de sincronización y otra para que el cliente inicie la sincronización.

2.1, crea un archivo de configuración rsync

Servidor de origen de sincronización:

[root@server-9~]# yum -y install httpd
//如果虚拟机是最小化安装,还需要rsync包安装。
[root@localhost ~]# yum -y install rsync

[root@server-9 ~]# vi /etc/rsyncd.conf               ####在同步源服务器上配置
uid = nobody
 gid = nobody
 use chroot = yes                            ####禁锢在源目录
 #address = XXXXXXXX                  ####监听地址
 port 873                                             ####监听端口号
 log file = /var/log/rsyncd.log            ####日志文件位置
 pid file = /var/run/rsyncd.pid            ####存放进程ID的文件位置
 hosts allow = 192.168.100.0/24          ####允许访问的客户机地址
[wwwroot]                                           ####共享模块名称
 path = /var/www/html                       ####源目录的实际路径
 comment = Document Root of www.51xit.top
 read only =yes                                   #####是否只读(手动同步为yes ,做自动同步需改为no)
 dont comperss = *.gz *.bz2 *.tgz *.zip *.rar *.z             ####同步时不在压缩的文件类型
 auth users =backuper                               #####授权账户
 secrets file = /etc/rsyncd_users.db                                         ####存放账户信息的数据文件

Por razones de seguridad, la fuente de sincronización solo debe permitir la sincronización de solo lectura. Además, la sincronización también puede ser anónima, siempre que la configuración de "auth users" "secrets file" esté comentada.

2.2. Cree un archivo de datos para la cuenta de respaldo

//创建rsync账号文件
采用“用户名:密码”的记录格式,每行一个用户记录,独立的账号数据,不依赖于系统账号
[root@server-9~]# vi /etc/rsyncd_users.db
backuper:pwd123

//由于账号信息采用明文存放,因此需要调整文件权限,避免账号信息泄露
[root@server-9 ~]# chmod 600 /etc/rsyncd_users.db 

2.3 Reinicie el servicio rsync para que sea efectivo

rsync --dameon 

//此处如果想要停止这个服务 ,有两个方式:
方式一:
[root@server-9 ~]# kill $(cat /var/run/rsyncd.pid)   #使用这个停止服务必须删除存放rsync服务进程的文件
[root@lserver-9 ~]# rm -rf /var/run/rsyncd.pid

方式二:直接使用“netstat -anpt | grep rsync”命令查出进程号,使用“kill 进程号”。

Prueba de sincronización Three. Rsync (tres métodos)

3.1 Escriba primero el archivo de prueba

[root@server-9 ~]# cd /var/www/html/
[root@server-9 html]# ls
[root@server-9 html]# echo "this is one" > /var/www/html/index.html
[root@server-9 html]# echo "this is web" > /var/www/html/web.html
[root@server-9 html]# ls
index.html  web.html

3.2 Realizar comandos de sincronización de operaciones en otros nodos

3.2.1 El primer método de sincronización

[root@SERVER 10 ~]# rsync -avz backuper@192.168.100.9::wwwroot /opt
Password:
receiving incremental file list
./
index.html
web.html

sent 65 bytes  received 199 bytes  40.62 bytes/sec
total size is 24  speedup is 0.09

3.2.2 El segundo método de sincronización

[root@SERVER 10 ~]# rsync -avz rsync://backuper@192.168.100.9/wwwroot /opt
Password:
receiving incremental file list

sent 20 bytes  received 90 bytes  12.94 bytes/sec
total size is 24  speedup is 0.22

3.2.3 El tercer método de sincronización, sin interacción

[root@SERVER 10 opt]# rm -rf *.html

创建密码文件
[root@SERVER 10 opt]# vim server.pass

abc123
~
~增加权限
[root@SERVER 10 opt]# chmod 600 server.pass
[root@SERVER 10 opt]# rsync -az --delete --password-file=/opt/server.pass backuper@192.168.100.9::wwwroot /opt
查看同步情况,同步成功
[root@SERVER 10 opt]# ls
index.html  web.html

3.2.4, configurar la sincronización regular

[root@SERVER 10 wwwroot]# crontab -e   ####每天晚上10点半对服务器网站目录更新一次
30 22 * * * /usr/bin/rsync -az --delete --password-file=/etc/server.pass backuper@192.168.100.41::wwwroot /opt/myweb/

[root@SERVER 10 wwwroot]# systemctl restart crond
[root@SERVER 10wwwroot]# systemctl enable crond

Four. Rsync + inotify herramienta de monitoreo para lograr la sincronización automática

Introducción a la sincronización en tiempo real
1. La sincronización periódica tiene algunas deficiencias, como:

El tiempo de ejecución de la copia de seguridad es fijo, el retraso es obvio y el rendimiento en tiempo real es deficiente.
Cuando la fuente de sincronización no cambia durante mucho tiempo, no se necesitan tareas periódicas intensivas.
2. Las ventajas de la sincronización en tiempo real

Una vez que cambie la fuente de sincronización, inicie inmediatamente la copia de seguridad
Siempre que la fuente de sincronización no cambie, no se realizará la copia de seguridad.
3. Introducción a inotify

A partir de 2.6.13, el kernel de Linux introdujo el mecanismo de notificación.
Es un mecanismo de notificación de cambios en el sistema de archivos, que
puede monitorear archivos y directorios.
Al monitorear un directorio, puede monitorear simultáneamente el directorio y cada subdirectorio y archivo en el directorio.
Puede ayudar a rsync, monitorear cambios de datos y activar rsync para sincronizar datos.
Inserte la descripción de la imagen aquí

4.1 Configurar en el servidor

vim /etc/rsync.conf

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

[wwwroot]
path = /var/www/html
comment = www
read only = no                   (自动同步改NO   ,手动同步改为yes )
auth users = backuper
secrets file = /etc/rsyncd_users.db

4.2 Crear texto de archivo de contraseña

vim /etc/rsync_users.db

backuper:abc123

chmod 600 /etc/rsyncd_users.db  //设置权限

4.3 Reiniciar el servicio

 kill 16360
netstat -ntap | grep rsync
rsync --daemon
 netstat -ntap | grep rsync

Instale la carpeta httpd, generate, var / www / html y otorgue permisos

yum  install httpd -y 

 cd /var/www
chmod 777 html


ll
总用量 0
drwxr-xr-x 2 root root 6 42 21:14 cgi-bin
drwxrwxrwx 2 root root 6 42 21:14 html

4.4 Configuración de inotify-tools en el lado del nodo

4.4.1 Instalar software de monitoreo

tar -zxvf inotify-tools-3.14.tar.gz
yum install  make  gcc gcc-c++ httpd -y
cd 进入目录
./configure
make && make install

4.4.2 Configuración del archivo del kernel

Cuando el número de directorios y archivos a monitorear es grande o los cambios son frecuentes, se recomienda aumentar los valores de estos tres parámetros.
Puede modificar directamente el archivo de configuración de /etc/sysctl.conf para configurar la cola de administración, la cantidad de instancias y la cantidad de monitoreo.

vim /etc/sysctl.conf
fs.inotify.max_queued_events = 16384
fs.inotify.max_user_instances = 1024
fs.inotify.max_user_watches = 1048576
 sysctl -p  // 立即生效

4.4.3 Crear texto de contraseña

vim /etc/server.pass
写入 abc123
[root@SERVER 10 /]# chmod 600 /etc/server.pass

4.4.4 Agregar permisos al directorio

[root@SERVER 10 /]# cd /var/www
[root@SERVER 10 www]# chmod 777 html

4.4.5 Prueba de seguimiento

[root@SERVER 10 ~]# cd /var/www/html/
[root@SERVER 10 html]# touch abc
[root@SERVER 10 html]# rm -rf abc


[root@SERVER 10 www]# inotifywait -mrq -e create,delete,move,modify,attrib,move,delete /var/www/html/
/var/www/html/ CREATE abc
/var/www/html/ ATTRIB abc
/var/www/html/ DELETE abc

4.4.6 Cree archivos de script para realizar la sincronización de monitoreo automática

vim /opt/intoify.sh
#!/bin/bash
INOTIFY_CMD="inotifywait -mrq -e create,delete,move,modify,attrib,move,delete /var/www/html/"
RSYNC_CMD="rsync -azH --delete --password-file=/etc/server.pass /var/www/html/ [email protected]::wwwroot/"

$INOTIFY_CMD | while read DIRECTORY EVENT FILE
do
    if [ $(pgrep rsync | wc -l) -le 0 ] ; then
        $RSYNC_CMD
#       echo "${FILE} was rsynced" >>/opt/inotify_rsync.log

    fi
done

Aumentar la autoridad de ejecución y ejecutar

chmod +x intoify.sh
./inotify.sh

4.4.7 Cree un archivo en el lado del directorio y véalo y pruébelo en otro lado del servidor

[root@SERVER 10 html]# echo "this is test" > test.html
[root@SERVER 10 html]# echo "this is test" > test2.html
[root@SERVER 10 html]# echo "this is test3" > test3.html
[root@SERVER 10 html]#
[root@SERVER 10 opt]# ./inotify.sh
rsync: failed to set times on "/." (in wwwroot): Operation not permitted (1)
rsync: chgrp "/.test.html.CMUx1o" (in wwwroot) failed: Operation not permitted (1)
rsync: chgrp "/.test2.html.QsPEBC" (in wwwroot) failed: Operation not permitted (1)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1178) [sender=3.1.2]
rsync: failed to set times on "/." (in wwwroot): Operation not permitted (1)
rsync: chgrp "/.test.html.WlvSvG" (in wwwroot) failed: Operation not permitted (1)
rsync: chgrp "/.test2.html.uKf5IU" (in wwwroot) failed: Operation not permitted (1)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1178) [sender=3.1.2]
rsync: failed to set times on "/." (in wwwroot): Operation not permitted (1)
rsync: chgrp "/.test.html.T8HIwo" (in wwwroot) failed: Operation not permitted (1)
rsync: chgrp "/.test2.html.QPx7rz" (in wwwroot) failed: Operation not permitted (1)
rsync: chgrp "/.test3.html.ZmVwnK" (in wwwroot) failed: Operation not permitted (1)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1178) [sender=3.1.2]
rsync: failed to set times on "/." (in wwwroot): Operation not permitted (1)
rsync: chgrp "/test3.html" (in wwwroot) failed: Operation not permitted (1)
rsync: chgrp "/.test.html.VG7wIt" (in wwwroot) failed: Operation not permitted (1)
rsync: chgrp "/.test2.html.xuuoiF" (in wwwroot) failed: Operation not permitted (1)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1178) [sender=3.1.2]

4.4.8 Verifique el servidor y descubra que la sincronización es exitosa

[root@server-9 html]# ls
test2.html  test3.html  test.html
[root@server-9 html]# cat test3.html
this is test3

Supongo que te gusta

Origin blog.csdn.net/BIGmustang/article/details/108530452
Recomendado
Clasificación