rsync+inotify实现远程实时同步

rsync介绍

rsync,英文全称是remote synchronize,是一款实现远程同步功能的免费软件,它在同步文件的同时,可以保持原来文件的权限、时间、软硬链接等附加信息。 rsync提供了一个客户机和远程文件服务器的文件同步的快速方法,而且可以通过ssh方式来传输文件。甚至还可以实现只同步一个文件里有变化的内容部分,所以可以实现快速的同步备份数据。同时,rsync还可以实现同步本地数据、删除文件和目录的功能。

inotify介绍

Inotify 是一个 Linux 内核特性,它监控文件系统,并且及时向专门的应用程序发出相关的事件警告,比如删除、读、写和卸载操作等。您还可以跟踪活动的源头和目标等细节。

rsync+notify实现自动同步

如果要实现定时同步数据,可以在客户端将rsync加入定时任务,但是定时任务的同步时间粒度并不能达到实时同步的要求。在Linux kernel 2.6.13后提供了inotify文件系统监控机制。通过rsync+inotify组合可以实现实时同步。

实验要求:

源服务器:192.168.177.132(rsync,httpd)

发起端:192.168.177.132(rsync,httpd,inotify-tools)

源服务器

# rpm -q rsync  //查看rsync有没有安装
# vim /etc/rsyncd.conf  //rsync的配置文件

 uid = nobody
 gid = nobody
 use chroot = yes
 address = 192.168.177.132
 port 873
 log file = /var/log/rsyncd.log
 pid file = /var/run/rsyncd.pid
 hosts allow = 192.168.177.0/24

 [wwwroot]
 path = /var/www/html
 comment = www.kgc.cn
 read only = yes
 dont compress  = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
 auth users = backuper
 secrets file = /etc/rsyncd_users.db
# vim /etc/rsyncd_users.db
  backuper:abc123  //账号跟密码的格式
# chmod 600 /etc/rsyncd_users.db
# yum install httpd -y  //安装web服务
# rsync --daemon  //启动rsync服务
# systemctl stop firewalld.service  //关闭防火墙
# setenforce 0  //增强性安全功能
# chmod 777 /var/www/html/
# cd /var/www/html
# echo "this is test" > 123.txt

发起端

# systemctl stop firewalld.service
# setenforce 0  //必须先关闭防火墙
交互,输入的是源服务器的地址
# rsync -avz [email protected]::wwwroot /opt/ 
免交互,无需输入密码
# vim /etc/server.pass
# chmod 600 /etc/server.pass
# rsync -az --delete --password-file=/etc/server.pass [email protected]::wwwroot /opt

rsync+inotify自动同步

inotify装在发起端

rsync在源服务器上

源服务器:
# vim /etc/rsyncd.conf
  read only = no
# pkill -9 rsync
# cd /var/run/
# rm -rf rsyncd.pid //删除pid进程
# rsync --daemon  //重启服务
发起端:
# chmod 777 /var/www/html/
# tar zxvf inotify-tools-3.14.tar.gz -C /opt //解压
# cd inotify-tools-3.14/
  ./configure
# yum install gcc gcc-c++ -y  //安装编译环境
# make && make install
# vim /etc/sysctl.conf  //进行优化
fs.inotify.max_queued_events = 16384
fs.inotify.max_user_instances = 1024
fs.inotify.max_user_watches = 1048576
# sysctl -p  //立即生效
# inotifywait -mrq -e modify,create,move,delete /var/www/html/  //对站点进行监控
# vim /opt/inotify.sh  //编写能同步的脚本
#!/bin/bash
INOTIFY_CMD="inotifywait -mrq -e modify,create,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
    fi
done
# chmod +x inotify.sh
# ./inotify.sh

猜你喜欢

转载自www.linuxidc.com/Linux/2018-08/153483.htm