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

相关推荐
无序的浪4 小时前
测试博客-基于微服务的在线判题系统
java·spring cloud·docker·微服务·测试·在线判题
溜达的大象8 小时前
极空间部署Traggo时间追踪工具:Docker安装、标签管理与cpolar远程访问
运维·docker·容器
脏脏a9 小时前
极空间部署 Dashlet:Docker 搭建私人导航仪表盘,再配置固定公网访问
运维·docker·容器
User_芊芊君子9 小时前
Prometheus接入Pushgateway实战:二进制与Docker部署、指标推送及远程上报
docker·容器·prometheus
databook10 小时前
手把手带你走一遍:机器学习模型如何用FastAPI和Docker部署
python·docker·fastapi
江湖有缘11 小时前
3款开源日记工具整理合集,可Docker一键部署!
docker·容器·开源
EatFans1 天前
Docker 实战部署:从本地镜像到云服务器,一篇走通 FastAPI + Celery + MySQL + Redis + Nginx
docker·fastapi
judezh1 天前
api 容器一直 unhealthy?我把一个 Agent 运行时的健康检查逐条拆了,查出四个问题
运维·docker
暗不需求1 天前
Docker 入门:从「光盘与 DVD」到全栈项目容器化实战
docker·容器·面试
探索云原生1 天前
一个 Deployment 就能跑 vLLM,为什么还需要 KServe?
docker·ai·云原生·kubernetes·go