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

相关推荐
BullSmall8 小时前
Sonarqube9.9 docker 镜像启动后 conf 下的配置文件没有了
docker·容器·eureka
ruofu338 小时前
wsl端是py312,但是项目是py311, 如何下载py311的依赖包(wheels)
python·docker
spider_xcxc9 小时前
Docker 实战:容器化多服务应用,Dockerfile 与 Compose 配置全解析
docker·云原生·eureka·虚拟化·容器化
晚风吹长发9 小时前
Docker使用——Docker容器及相关命令
linux·运维·服务器·docker·容器·架构
ShiXZ21310 小时前
Docker Compose 安装与配置指南
运维·docker·容器
BullSmall11 小时前
Anolis OS 8.10 Docker 部署 SonarQube 9.9 完整教程
运维·docker·容器
开发者联盟league11 小时前
vscode 进入docker容器
vscode·docker
java_logo14 小时前
Apache Doris Docker 部署指南:实时分析数据库实战
数据库·docker·apache·doris·apache doris·轩辕镜像·docker部署doris
生活爱好者!1 天前
我把NAS当作下载机,docker一键部署qb
运维·docker·容器
java_logo1 天前
Docker Compose 部署 ClickHouse:快速搭建高性能列式数据库
数据库·clickhouse·docker·列式数据库·轩辕镜像·高性能数据库·clickhouse部署教程