【Rsync + inotify】 实时同步远程服务器目录文件

服务端

安装、配置 rsync

centos:
# yum install rsync -y 

# vim /etc/rsyncd.conf
uid = nobody
gid = nobody
use chroot = yes
max connections = 10
strict mode=yes
pid file = /var/run/rsyncd.pid
lock file=/var/run/rsync.lock
log file=/var/log/rsyncd.log
[backup]  # 自定义模块名称
  path = /home/dstdir/  # 目标目录
  comment = test # 描述信息
  ignore errrors
  read only=no
  write only=no
  hosts allow=1.1.1.0/24
  hosts deny=*
  list=false
  uid=root
  gid=root
  auth users=backupuser  # 自定义名称
  secrets file=/etc/rsyncd.pwd

##  用户名:密码,要求用户名backupuser 与 /etc/rsyncd.conf 的auth users 一致
# echo "backupuser:123456" > /etc/rsyncd.pwd  

## 启动服务
# /etc/init.d/rsyncd start

## 默认为 873 端口,配置防火墙
iptables -A INPUT -p tcp --dport 873 -j ACCEPT && iptables-save

ubuntun:
apt install rsync
.....配置大致相同,不在赘述


客户端

安装rsync

与服务端相同,客户端不用配置,只需启动服务(/etc/init.d/rsyncd startsystemctl start rsyncd),并使用即可

使用rsysnc

## 只需要写入backupuser 的密码即可
# echo "123456" > /etc/rsync.pwd 

# chmod 600 /etc/rsync.pwd

## /usr/bin/rsync -vzrtopg --delete --progress --password-file=<密码文件> <源目录> <auth users>@<服务端地址>::<服务端定义的模块名>
/usr/bin/rsync -vzrtopg --delete --progress --password-file=/etc/rsync.pwd /home/src/ [email protected]::backup

实现 实时同步

## 安装 inotify
yum install inotify-tools

## 写脚本 inotify_rsync.sh
/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e close_write,delete,create,attrib $src | while read files
do
  /usr/bin/rsync -vzrtopg --delete --progress --password-file=/etc/rsync.pwd /home/src/ [email protected]::backup > /dev/null 2>&1
  echo "${files} was rsynced." >> /tmp/rsync.log 2>&1
done

chmod +x inotify_rsync.sh

## 前台执行,并调试
bash inotify_rsync.sh

再打开新窗口连接客户端,在原目录下创建文件a.test (touch /home/src/a.test)
查看客户端日志,并去服务端目标目录是否有新文件a.test

如果没有问题,那关闭前台命令 ,先ps -ef |grep ino 查看进程号,再 kill -9 <进程号> 杀死进程

## 后台执行
nohup inotify_rsync.sh & 


如何排错???

可以在服务端转包,查看数据是否有新数据过来,示例: tcpdump -nn -i eth1 port 873

猜你喜欢

转载自blog.csdn.net/qq_22227087/article/details/113576398