原理:
rsync:用于跨主机目录同步
inotify:用于监测目录变化
再编写一个触发脚本,一旦inotify检测到目录中内容发生变化,则调用rsync执行同步。
rsync服务器的的配置:
因为rsync是被xinetd守护,所以需要首先安装xinetd程序。
服务端配置:
安装阿里云epel源:
rpm -ihv https://mirrors.aliyun.com/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install xinetd -y 安装守护进程xinetd
service xinetd start
yum install rsync -y 安装rsync
使xinetd监听rsync:
vim /etc/xinetd.d/rsync #启用rsync
将其中的disable = yes 改为disable = no
service xinetd restart
编辑主要配置文件 /etc/rsyncd.conf 这个文件需要自己创建
vim /etc/rsyncd.conf
uid = root
gid = root
use chroot = no
max connections = 4
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
log file = /var/log/rsyncd.log #最好指明日志文件目录,一旦出错才好查看日志排查
[web]
path = /rsync
list = false
read only = no 一定要关闭只读,因为默认只读客户端是没有权限拉取数据的。
#hosts allow = 192.168.9.195/255.255.255.0
#hosts deny = 0.0.0.0/32
auth users = test #指明用于认证的用户,到时候其它主机来同步文件就要以这个用户的身份
secrets file = /etc/test.pass #指明用于保存密码的文件路径
每一个“[]”下面的为一个模块,path是它所映射的目录,当同步这个模块时,便是同步path下面的目录中的内容
编辑服务器的密码文件 /etc/test.pass
vim /etc/test.pass
test:123456 这个用户和密码需要是实际存在的系统用户,到时候客户端来同步数据时就是以这个身份
chmod 600 /etc/test.pass
客户端配置:
客户端主要是要去同步服务端的配置,rsync默认是安装了的,若没有可以自行安装
yum install rsync -y 安装rsync
编辑rsync连接时的密码文件 /etc/rsync_client.pass
vim /etc/rsync_client.pass
123456 # 只需要配置连接时使用的密码即可,必须与服务器上定义的密码相同.
chmod 600 /etc/rsync_client.pass
配置好服务端和客户端之后就可以进行同步测试了
rsync命令的使用:
rsync 可以相当于复制命令,会将指定内容复制到目标位置
-a 保留文件所有属性复制
-n:测试,在不确定命令是否能按照意愿执行时,务必要实现测试
-v:详细输出模式,--verbose
-q:--quiet,静默模式
-c:--checksum,开启校验功能,强行对文件传输进行校验
-r:--recursive,递归复制
-a: --archives.归档,保留文件的原有属性相当于rlptgoD的选项组合wKioL1gEMvXRMZ5SAAAitet95ug281.png-p:--perms 保留文件的权限
-t: --times 保留文件的时间戳
-l:--links 保留文件的符号链接
-g:--group保留文件的属组
-o:--owner 保留文件的属主
-D:--devices 保留设备文件
-e ssh:表示使用ssh协议作为继承
-z:对文件压缩后传输
--progress:显示进度条
注意:
rsync命令使用中,如果源参数的末尾有斜线,只会复制指定目录的内容,而不复制目录本身,没有斜线,则会复制目录本身,包括目录
客户端从服务端拉取数据:
rsync -avzP [email protected]::web /rsync --password-file=/etc/rsync_client.pass
客户端向服务端推送数据:
rsync -avzP /rsync [email protected]::web --password-file=/etc/rsync_client.pass
安装inotify:
yum install inotify-tools -y
安装之后会在服务器上生成两个二进制程序:inotifywait inotifywatch
我们主要是利用inotifywait 来监测目录变化。
在客户端添加实时同步脚本:
#!/bin/bash
# tools : inotifywait and rsync
/usr/bin/inotifywait -mrq --exclude '.*/*\.(swp|swx|.*~)$' --timefmt '%y/%m/%d/%H:%M' --format '%T %w %f %e' -e modify,delete,create,move /rsync | while read events ; do
rsync -vzrtopg --progress --delete --password-file=/etc/rsync_client.pass /rsync [email protected]::web
done
之后将脚本挂在后台运行就可以了