ECS多主机之间文件同步rsync+inotify
1. 环境
[1] server1:10.0.0.0.200 -> Rsync服务端,需要配置rsync.conf
[2] server2: 10.0.0.0.201 -> Rsync服务端,需要配置rsync.conf
[3] 数据发布端: 10.0.0.202 -> Rsync客户端(不需要配置rsync.conf) + inotify(实时监听文件变化,实时通过rsync推送更新到服务器)
2. 准备
[1] 关闭firewalld,永久关闭selinux, 没开启跳过
[2] 安装依赖包
# yum install -y lrzsz gcc wget gcc-c++ vim
3. 服务端安装
[1] 安装rsync
#yum install -y rsync
[2] 更改配置
#vim /etc/rsyncd.conf
[3] 配置内容rsyncd.conf
#vim /etc/rsync.password
#chmod 600 /etc/rsync.password
#工作中指定用户(可以不指定为0, 不能是nobody)
uid = 0
gid = 0
#相当于黑洞.出错定位
use chroot = no
##有多少个客户端同时传文件
max connections =200
##超时时间
timeout = 300
##进程号文件
pid ifle = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
##日志文件
log file = /var/log/rsyncd.log
##模块开始(这个模块就是待会儿对端写脚本的里面一个参数的名称)
[msone]
##需要同步的目录(准确的说是同步过来后放到哪里的目录路径)
path = /home/wwwroot
##表示出现错误忽略错误
ignore errors
##表示网络权限可写(本地控制真正可写)(亲测这里写false报错)
read only = no
##这里设置IP或让不让同步
list = false
#允许的ip或者ip段
hosts allow = 0.0.0.0/32
##拒绝,以下表示都不拒绝
hosts deny = 0.0.0.0/32
##认证用户
auth users = rsynclsl
##用户名和密码存放文件
secrets file = /etc/rsync.secrets
[4] 添加同步需要用的用户名和密码(123456)
#useradd -s /sbin/nologin rsynclsl
#passwd rsynclsl
[5] 创建认证文件, 为了安全起见给这个文件设置600权限。
#vim /etc/rsync.secrets
文件里面添加如下内容(格式为用户名:密码):
rsynclsl:123456
#chmod 600 /etc/rsync.secrets
[6] 同步目录
#mkdir /home/wwwroot
#chmod 765 /home/wwwroot
4. 客户端安装
[1] 安装rsync和inotify(rsync只安装不启动不配置)
#yum install -y rsync
#yum install -y inotify-tool
[2] 创建/etc/rsync.password文件(整个文件需要600的权限和服务端rsync同步用户的密码,这里是服务器端rsynclsl用户的密码)
#vim /etc/rsync.password
#chmod 600 /etc/rsync.password
[3] 测试rsync配置是否成功安装
#rsync -avH --port=873 --delete /home/wwwroot/ rsynclsl@10.0.0.201::msone --password-file=/etc/rsync.password
[4] 编写inotify触发同步脚本:
#!/bin/bash
#chkconfig: 345 88 14
src_dir="/home/wwwroot/"
dst_dir="msone"
exclude_dir="/home/shell/inotify/exclude.list"
rsync_user="rsynclsl"
rsync_pass="/etc/rsync.password"
dst_ip="10.0.0.200 10.0.0.201"
rsync_command(){
rsync -avH --port=873 --progress --delete --exclude-from=$exclude_dir $src_dir $rsync_user@$ip::$dst_dir --password-file=$rsync_pass
}
for ip in $dst_ip;
do
rsync_command
done
/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e close_write,modify,delete,create,attrib,move $src_dir | while read file;
do
for ip in $dst_ip;
do
rsync_command
datetime=`date +"%Y%m%d"`
echo "${file} was rsynced" >> /home/shell/inotify/log/${datetime}.log 2>&1
done
done
[5] 配置开机启动同步脚本
(1)#vim /etc/rc.d/rc.local
追加内容: nohup /bin/sh /home/shell/inotify/rsync.sh &
(2)在centos7中,/etc/rc.d/rc.local的权限被降低了,所以需要执行如下命令赋予其可执行权限
#chmod +x /etc/rc.d/rc.local