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

相关推荐
修罗王10 小时前
Linux Docker 服务管理与排查实战指南(新手速查版)
运维·docker
张龙68712 小时前
Docker 镜像瘦身实战:从 1.2GB 到 128MB,我踩过的 7 个坑和一套可复制的方法论
运维·后端·docker
杨浦老苏14 小时前
开源堡垒机 Warpgate:一个容器搞定 SSH、MySQL 和 Web 访问
运维·docker·ssh·堡垒机·群晖
ERD Online14 小时前
docker-compose 一键部署的 MIT 开源数据库建模平台
数据库·docker·开源
三言老师16 小时前
CentOS7.9 + Kubernetes 1.18.20 -清理所有 docker / containerd 残留
docker·容器·kubernetes
circuitsosk16 小时前
从Docker到Kubernetes:AI应用服务化与弹性伸缩的落地实践
人工智能·docker·kubernetes·ai应用部署
showyoui17 小时前
K8s 集群迁移踩坑:Istio 升级后 nginx 403
网络·docker·kubernetes·istio·service_mesh
golang学习记1 天前
Go 项目使用docker compose的正确方式
开发语言·docker·golang
雨声不在2 天前
私有 Docker Registry 排障实录:两个隐蔽的坑
docker·容器
读书读傻了哟2 天前
解决docker拉取镜像报错failed to resolve reference “docker.io/xxx“...i/o timeout问题
运维·docker·容器