最近由于某些原因需要同步备份到备份服务器,但定时同步效果不太好,所以就换成了实时同步
rsync是linux系统下的数据镜像备份工具,支持本地复制,或者与其他SSH、rsync主机同步
inotify可以用来监控文件系统操作,如创建、删除、读取、写入等
#!/bin/bash
## this script is used for sync local files to the rsync server in real time
## written by landzf
## date: 2021/02/04
## 安装系统监控工具inotify-tools
yum -y install inotify-tools
## 编写脚本实时监控本地备份目录并同步备份文件到备份服务器
mkdir -p /etc/backup/real-time-sync.sh
cat >> /etc/backup/real-time-sync.sh <<- EOF
#!/bin/bash
inotifywait -mrq --timefmt '%Y-%m-%d %A %H:%M' --format '%T %w%f' -e close_write,delete,create,attrib,move /backup/ |while read file
do
rsync -vrtazp --delete --progress /backup/ rsync://backup.landzf.cn/backup/
done
EOF
## 配置脚本作为系统服务
cat >> /lib/systemd/system/real-time-sync.service <<- eof
[Unit]
Description=Real-time Sync Service
After=network.target syslog.target
Wants=network.target
[Service]
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/etc/backup/real-time-sync.sh start
[Install]
WantedBy=multi-user.target
eof
## 启动服务并设置开机自启
systemctl daemon-reload
systemctl start real-time-sync.service
systemctl enable real-time-sync.service