一. inotify的简介
Inotify 是一个 Linux特性,它监控文件系统操作,比如读取、写入和创建。Inotify 反应灵敏,用法非常简单,并且比 cron 任务的繁忙轮询高效得多。学习如何将 inotify 集成到您的应用程序中,并发现一组可用来进一步自动化系统治理的命令行工具。
二. 需求背景
文件服务器1(主服务器):172.16.20.20
文件服务器2(从服务器):172.16.30.20
在故障发生后能够切换到2服务器进行工作
三. 安装软件
pacman -S inotify-tools
四.编写监控脚本
#!/bin/bash
# 服务器地址
host=172.16.30.20 # rsync服务器地址
src=/var/horee/store # 本地监控的目录
dst=store # rsync服务器的模块名称
user=sync # rsync服务器的虚拟用户
passfile=/etc/password.rsync # 本地调用rsync服务的密码文件
# 判断先决条件
if [ ! -e "$src" ] || [ ! -e "${passfile}" ] || [ ! -e "/usr/bin/inotifywait" ] || [ ! -e "/usr/bin/rsync" ]; then
echo "Check File and Folder"
exit 9
fi
/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e close_write,delete,create,attrib $src |
while read file; do
cd $src && rsync -aruz -R --delete ./ --timeout=100 $user@$host::$dst --password-file=${passfile} >/dev/null 2>&1
done
exit 0
五.启动同步
sh inotify.sh &