服务端
linux下实现实时文件同步

步骤


  1. 安装 inotify-tools 和 rsync
    • Debian/Ubuntu
bash
sudo apt-get update sudo apt-get install inotify-tools rsync 

  • CentOS/RHEL
bash
sudo yum install inotify-tools rsync 

  1. 配置 SSH 密钥认证(可选但推荐)
    • 生成 SSH 密钥对:
bash
ssh-keygen -t rsa 

  • 将公钥复制到目标服务器:
bash
ssh-copy-id user@destination_server_ip 

  1. 编写监控脚本
    • 创建一个名为 sync_monitor.sh 的脚本:

bash

#!/bin/bash 

# 源目录 

SOURCE_DIR="/path/to/source/config/files" 

# 目标服务器和目录 

DESTINATION="user@destination_server_ip:/path/to/destination/config/files"

# 监控源目录的变化 

inotifywait -m -r -e create,delete,modify,move $SOURCE_DIR | while read path action file; do 

# 当文件发生变化时,使用 rsync 进行同步 

    rsync -avz --delete $SOURCE_DIR/ $DESTINATION 

done


  1. 赋予脚本执行权限
bash
chmod +x sync_monitor.sh 

  1. 运行脚本
bash
./sync_monitor.sh 

为了让脚本在后台持续运行,可以使用 nohup 命令:
bash
nohup ./sync_monitor.sh &