同步两个机器上的/data目录,做到时刻数据一致 ,
在主所在的机器上,首先创建/script目录,编写rsync.sh主从同步的脚本

#!/bin/bash
srcdir=/data/       ##需要同步的目录
dstdir=web         ##从机上编写的模块
excludedir=/script/exclude_list         ##例外文件,这里面写的目录都不进行同步
rsyncuser=webuser       ##从机上定义的用户名
rsyncpass=/script/web_pass     ## 密码所在的文件
dstip="10.167.5.14"     ##从机的ip

for ip in $dstip; do
    rsync -avH --progress --delete --exclude-from=$excludedir $srcdir $rsyncuser@$ip::$dstdir --password-file=$rsyncpass
done

/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e close_write,modify,delete,create,attrib,move $srcdir |  while
 read file; do  
    for ip in $dstip; do
      rsync -avH --progress --delete --exclude-from=$excludedir $srcdir $rsyncuser@$ip::$dstdir --password-file=$rsyncpass
      echo "  ${file} was rsynced" >> /tmp/rsync.log 2>&1
    done
done

 

 

2. 从机配置
同样创建/script目录,里面制定web_pass文件以及其密码

 

 然后vim /etc/rsyncd.conf  ,在最后添加一下模板,注意web模块里不要加注释,会影响读取。

uid = nobody
gid = nobody
use chroot = yes
max connections = 4
pid file = /var/run/rsyncd.pid
transfer logging = yes

[web]
       path = /data/       ##要同步的目录
       ignore errors = yes
       read only = no
       write only = no
       hosts allow = 10.167.5.13      ##允许哪台主机进行同步
       list = false
       uid = www      ##设置要同步的目录所属者,所属组以及权限
       gid = www
       auth users = webuser     ##指定定用户名
       secrets file = /script/web_pass    ##账号密码所在文件

##修改配置文件后注意重启服务 systemctl restart rsyncd
##关闭selinux以及防火墙
!!!注意 !!!
1,rsync的web_pass文件权限有必须的要求,要设置为600,主机从机都一样!
2,记着更改要同步的目录,例如data目录的所属者和所属组为www,主机和从机都是,所属者在从机的/etc/rsyncd.conf里配置
3,后台启动nohup脚本,重启服务记得杀掉上次起来的进程
有的系统没有安装文件监控,需要安装 yum install -y inotify-tools 来实现文件监控
nohup sh /script/rsync.sh > /dev/null 2>&1 &

 posted on 2020-01-09 16:06  小巷的汪  阅读(287)  评论(0编辑  收藏  举报