inotify+rsync 自动同步systemctl服务

安装inotify

sudo apt update
sudo apt install inotify-tools rsync -y

centos/RHEL系列用dnf安装

 

mkdir /opt/rsync_watch/
cat >/opt/rsync_watch/rsync_watch.sh<<'EOF'
#!/bin/bash

# 加载配置文件
ENV_FILE="/opt/rsync_watch/rsync_watch.env"
if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | xargs)
fi

# 检查必需变量
if [ -z "$LOCAL_DIR" ] || [ -z "$REMOTE_USER" ] || [ -z "$REMOTE_HOST" ] || [ -z "$REMOTE_DIR" ] || [ -z "$RSYNC_PORT" ]; then
    echo "请先在 $ENV_FILE 配置 LOCAL_DIR, REMOTE_USER, REMOTE_HOST, REMOTE_DIR, RSYNC_PORT"
    exit 1
fi

# RSYNC SSH 参数
RSYNC_SSH="ssh -p ${RSYNC_PORT}"

# RSYNC 默认选项
RSYNC_OPTS=${RSYNC_OPTS:-"-az --delete --exclude='.git/'"}

echo "Starting initial sync..."
rsync $RSYNC_OPTS -e "$RSYNC_SSH" --progress --itemize-changes "$LOCAL_DIR/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"

echo "Watching for changes in $LOCAL_DIR ..."
inotifywait -m -r -e modify,create,delete,move --format '%w%f' "$LOCAL_DIR" |
while read -r FILE; do
    echo "$(date '+%F %T') Detected change: $FILE"
    rsync $RSYNC_OPTS -e "$RSYNC_SSH" --progress --itemize-changes "$LOCAL_DIR/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"
done
EOF

 

/opt/rsync_watch/rsync_watch.env配置文件

LOCAL_DIR=/path/to/local/dir
REMOTE_USER=user
REMOTE_HOST=remote.host.com
REMOTE_DIR=/path/to/remote/dir
RSYNC_PORT=2222
RSYNC_OPTS="-az --exclude='.git/'"

 

systemd配置

cat>/etc/systemd/system/rsync_watch.service<<EOF
[Unit]
Description=Rsync Watcher for Directory
After=network.target

[Service]
Type=simple
ExecStart=/opt/rsync_watch/rsync_watch.sh
Restart=always
RestartSec=5
User=root
WorkingDirectory=/opt/rsync_watch
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload # 重新加载 systemd 配置
sudo systemctl enable rsync_watch --now # 开机自启
sudo systemctl status rsync_watch # 查看状态

添加新评论 »