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

相关推荐
IT成长日记39 分钟前
【Docker基础】Docker核心概念:容器(Container)与镜像(Image)的区别与联系
运维·docker·区别与联系·container·imgae
xixingzhe21 小时前
docker compose安装Prometheus、Grafana
docker·grafana·prometheus
Kevin不想说话926192 小时前
WSL2 Ubuntu Docker 完整部署指南
docker
啃火龙果的兔子3 小时前
在服务器上使用 Docker 部署 Node.js 后端服务和前端项目
服务器·docker·node.js
风清再凯3 小时前
docker-compose容器单机编排
docker·容器·dubbo
ℳ₯㎕ddzོꦿ࿐4 小时前
Ubuntu 24.04 上安装与 Docker 部署 Sentinel
ubuntu·docker·sentinel
masx2006 小时前
minio web console已死,Web管理功能全砍!使用 OpenMaxIO 恢复 MinIO 社区版的 Web 控制台功能!
docker·容器
爱学语言的人7 小时前
Docker快速构建并启动Springboot程序,快速发布和上线/
spring boot·docker·容器
大千AI助手7 小时前
5分钟玩转Swagger UI:Docker部署+静态化实战
ui·docker·容器·swagger·swaggerui
江湖有缘7 小时前
【Docker管理工具】安装容器管理工具Oxker
运维·docker·容器