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

相关推荐
IT19952 小时前
Docker笔记-对docker-compose.yml基本认识
笔记·docker·容器
supersolon4 小时前
WSL2(Linux)升级docker
linux·运维·docker·wsl·升级
一殊酒5 小时前
【Docker】常用命令大全及解析
docker·容器·eureka
Uncertainty!!5 小时前
将docker镜像上传到github镜像存储仓库(GitHub 容器仓库(GHCR)使用流程)
docker·容器·github
我是谁??6 小时前
Rocky9+ Docker + 容器内Linux桌面环境 + Web远程
运维·docker·容器
姓王名礼6 小时前
这是一个完整的全栈交付包,包含Vue3 前端交互界面(集成数字人视频流、ECharts 图表、语音对话)和Docker Compose 一键部署脚本。
前端·docker·echarts
eggwyw7 小时前
Redis 设置密码(配置文件、docker容器、命令行3种场景)
数据库·redis·docker
赵文宇(温玉)8 小时前
Openclaw-In-Docker新版本发布,更轻、更快、更健壮,1600+次下载,30+Github关注
docker·容器·github·小龙虾·clawclaw
badhope8 小时前
Docker入门到实战全攻略
linux·python·docker·github·matplotlib
daydayup95278 小时前
swarm安装使用(二)
docker·云原生·容器