shell实现两台服务器的文件实时同步

背景

如果要实现两台服务器的文件的热备份,要怎么做呢?使用shell脚本可以轻松实现。

分析

实现文件实时监控的命令为:inotifywait。

当文件有新增、修改、删除等操作时,这个文件监控就会触发事件,来通知你。

文件同步的命令为:rsync。

这个可以将文件从一台服务器快速同步到另外一台服务器。

将inotifywait 和 rsync 结合起来就可以实现实时同步的热备效果了。

下面是完整的脚本:

#!/bin/bash

CONFIG_FILE="config.txt"

读取配置文件,格式为:源目录:目标目录

read_config_file() {

while IFS=: read -r source_dir target_dir; do

if [[ source_dir \&\& target_dir ]]; then

inotifywait -m -r -e modify,create,delete "$source_dir" |

while read path action file; do

rsync -avz "source_dir/" root@目标IP:"target_dir/"

done &

fi

done < "$CONFIG_FILE"

}

主函数入口

main() {

if [[ -f "$CONFIG_FILE" ]]; then

read_config_file

else

echo "配置文件 $CONFIG_FILE 不存在."

fi

}

执行主函数

main

配置文件config.txt:

/data/sync/watched:/data/sync/watched

总结

文件实时同步,借助inotifywait 和 rsync 就可以轻松实现。

来源: http://www.yu7s.com/article/20240329115541120.html

相关推荐
春风有信44 分钟前
【2026.05.01】Windows10安装Docker Desktop 4.71.0.0步骤及问题解决
运维·docker·容器
sthnyph5 小时前
docker compose安装redis
redis·docker·容器
W.A委员会6 小时前
Docker基本使用流程
运维·docker·容器
GuokLiu7 小时前
260502-Clawith-Docker安装过程
运维·docker·容器·claw
JesseDev8 小时前
Docker lnmp环境快速搭建开箱即用
运维·docker·容器
空中海9 小时前
Docker入门到精通
java·docker·eureka
BduL OWED10 小时前
Docker:基于自制openjdk8镜像 or 官方openjdk8镜像,制作tomcat镜像
docker·容器·tomcat
.柒宇.10 小时前
AI掘金头条项目 Docker Compose 部署完整教程(附踩坑记录)
运维·后端·python·docker·容器·fastapi
运维全栈笔记1 天前
K8S部署Redis高可用全攻略:1主2从3哨兵架构实战
redis·docker·云原生·容器·架构·kubernetes·bootstrap
SCBAiotAigc1 天前
2026.5.1:`DockerDesktop must be owned by an elevated account`错误的解决办法
人工智能·docker·具身智能