设置配置环境
主机A | 192.168.226.169 |
---|
主机B | 192.168.226.131 |
关闭防火墙和selinux:
[root@localhost ~]# systemctl stop firewalld.service
[root@localhost ~]# setenforce 0
ssh免密登录
[root@localhost ~]# ssh-keygen
[root@localhost ~]# ssh root@192.168.226.131
测试
[root@localhost ~]# ssh-copy-id root@192.168.226.131(记得退出登录exit)
创建目录
#主机A
[root@localhost ~]# mkdir test1
#主机B
[root@localhost ~]# mkdir test2
主机AB都安装rsync
安装rsync
[root@localhost ~]# yum -y install rsync
查看rsync是否存在
[root@localhost ~]# rpm -qa | grep rsync
rsync-3.1.2-10.el7.x86_64
创建文件并上传
#主机A
[root@localhost ~]# cd test1/
[root@localhost test1]# touch 1.txt
[root@localhost ~]# rsync /root/test1/* root@192.168.226.131:/root/test2/
#主机B
[root@localhost ~]# ls test2/
1.txt
安装inotify
主机A
安装epel源
[root@localhost ~]# yum -y install epel-release.noarch
安装inotify
[root@localhost ~]# yum -y install inotify-tools
实现rsync+inotify实时备份
#主机A
[root@localhost ~]# vim /etc/rsyncd.conf
prot = 873 #端口
address = 192.168.226.169 #IP
uid = root #用户
gid = root #组
use chroot = no #不使用root切换模式
max connections = 0 #没有连接数
pid file = /var/run/rsyncd.pid #pid文件
exclude = lost+found/ #同步数据是,排除lost+found这个目录
transfer logging = yes #打开日志
log file = /var/lib/rsync.log #日志文件存放位置
timeout = 900 #超时时间
ignore nonreadable = yes #忽略没有权限的用户
dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2 #遇到这类文件不进行压缩
[test] #同步模块名
path = /test1 #监控的目录
comment = test1 #备注
read only = no #不是只读
[root@localhost ~]# systemctl start rsyncd #开启rsync
[root@localhost ~]# netstat -anpt | grep 873
tcp 0 0 192.168.226.169:873 0.0.0.0:* LISTEN 15032/rsync
编写备份脚本
#主机A
[root@localhost ~]# vim inotify.sh
#!/bin/bash
/usr/bin/inotifywait -mrq --format %w%f -e create,delete,close_write /root/test1 | while read file
do
if [ -f $file ];then
rsync -a --delete $file root@192.168.226.131:/root/test2
else
rsync -a --delete /root/test1/ root@192.168.226.131:/root/test2
fi
done
[root@localhost ~]# chmod +x inotify.sh #执行权限
[root@localhost ~]# ./inotify.sh & #后台运行
验证是否成功
#主机A
[root@localhost ~]# cd test1/
[root@localhost test1]# touch aaa
[root@localhost test1]# ls
1.txt aaa
#主机B
[root@localhost ~]# cd test2/
[root@localhost test2]# ls
1.txt aaa
#主机A
[root@localhost ~]# cd test1/
[root@localhost test1]# rm -rf *
[root@localhost test1]# ls
#主机B
[root@localhost ~]# cd test2/
[root@localhost test2]# ls