Linux, 应用部署

rsync+inotifywait 实现文件夹远程实时同步

一、介绍

1、rsync

rsync(Remote Sync,远程同步)是一款可以实现快速增量备份的工具。配合任务计划,rsync能实现定时或间隔同步,配合inotify,可以实现触发式的实时同步。rsync系统默认已经安装。

2、inotifywait

inotify 是一个 Linux 内核特性由inotify-tools包提供,它监控文件系统,并且及时向专门的应用程序发出相关的事件警告,比如删除、读、写和卸载操作等。

 安装inotify-tools:  
  
[root@localhost ~]# yum -y install inotify-tools

二、服务端rsync配置

[root@T1 ~]# grep -Ev "^$" /etc/rsyncd.conf
# /etc/rsyncd: configuration file for rsync daemon mode
# See rsyncd.conf man page for more options.
# configuration example:
uid = nobody
gid = nobody
#use chroot = yes
max connections = 4
pid file = /var/run/rsyncd.pid
exclude = lost+found/
#transfer logging = yes
#timeout = 900
ignore nonreadable = yes
dont compress   = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
#hosts allow =192.168.0.0/16
[ftp]
      path = /var/log
#        comment = ftp export area
auth users=shs
secrets file = /etc/rsyncd.user
read only = no

[root@T1 ~]# cat /etc/rsyncd.user 
shs:123456abc
[root@T1 ~]# chmod 600/etc/rsyncd.user

三、inotifywait与rsync配合实现实时远程同步

rsync 常用参数:

-a    归档
-r    递归
-z    压缩传输
-v    显示详细信息
-e    调用远端sh
-H    传输硬链接

rsync 资源的两种表示方法:

rsync://remote_user@remote_host/sharemode
remote_user@remote_host::sharemode 

注意::与单:的区别 
  当rsync使用ssh作为传输通道时,调入ssh的认证,并使用:作为主机与路径的分隔符,如:
rsync -avz -e"ssh"   /path/to/localfile  remote_sys_user@remote_host:/path/to/file
  而::是作为rsync主机与共享模块之间的分隔符,这时候调用rsync的用户密码进行认证。

以下是一个使用 inotifywait 和 rsync 配合实现实时远程同步的示例脚本:

#!/bin/bash

# 本地目录
local_dir="/path/to/local/directory"

# 远程主机信息
remote_user="your_username"
remote_host="your_remote_host"
remote_dir="/path/to/remote/directory"
rsyncd_pwd="/path/to/rsyncd_pwd"

# 监控本地目录的修改、创建和删除事件
inotifywait -mrq --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %w%f %e' "$local_dir" | while read date time file event
do
    # 当有事件发生时,执行 rsync 同步
    rsync -avz --delete --password-file=$rsyncd_pwd "$local_dir" "$remote_user@$remote_host::$remote_dir"
    echo "[$date $time] File: $file, Event: $event"
done

注意:

1、rsync服务器端启用密码认证时,密码文件的权限必须设置为600,否则客户端无法登录。

2、rsync客户端使用密码文件登录时,密码文件的权限必须设置为600。密码文件内容直接写密码即可。

3、rsync共享文件夹默认为只读模式,如需要写入文件需要在共享模块设置下修改:read only = no

Leave a Reply