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

相关推荐
辉的技术笔记3 小时前
Dify 自部署为什么跑不动?6 层瓶颈诊断法教你定位
docker
程序员老赵1 天前
Docker 部署 Redmine:老牌开源项目管理部署实测记录
docker·开源·团队管理
程序员老赵1 天前
服务器文件不想 SFTP 上传?Docker 跑个 File Browser,浏览器就能管理
服务器·docker·开源
lichenyang4533 天前
Docker 学习笔记(五):Docker Compose,用一个 YAML 启动前端、后端和 MongoDB
docker
lichenyang4533 天前
Docker 学习笔记(四):Dockerfile,把项目打成自己的镜像
docker·容器
lichenyang4533 天前
Docker 学习笔记(三):Docker 网络、bridge、子网和容器互通
docker·容器
lichenyang4533 天前
Docker 学习笔记(二):docker run 的参数到底在控制什么?
docker·容器
Patrick_Wilson8 天前
从「改个端口」到 502:Next.js on k8s 的容器端口、Service 映射与 env 覆盖
docker·kubernetes·next.js
Suroy8 天前
DockerView-Go:用 Go 写一个终端 Docker 监控工具,顺便做了个 Web 仪表盘
docker
云恒要逆袭8 天前
运行你的第一个Docker容器
后端·docker·容器