inotify+rsync实现实时同步(附解决crontab中无法执行python脚本的问题)

时间:2021-11-25 17:16:23

1.准备环境

# 系统支持的话,下面的目录就会存在
ls /proc/sys/fs/inotify/
rpm -qa inotify-tools
yum -y install inotify-tools

2.inotifywait监控目录状态变化

/usr/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e delete,create,close_write /data
# 可以把时间去掉
/usr/bin/inotifywait -mrq --format '%w%f' -e delete,close_write /data

3.循序渐进的同步脚本

#!/bin/bash
Path=/data
Ip=172.16.1.41
/usr/bin/inotifywait -mrq --format '%w%f' -e delete,close_write $Path | while read file
do
cd $Path &&\
rsync -az ./ --delete rsync_backup@172.16.1.41::nfsbackup --password-file=/etc/rsync.password
done
# 上边那个脚本效率很低,效率低的原因在于只要目录出现变化就都会导致我整个目录下所有东西都被推送一遍.
# 因此,我们可以做如下改动提高效率.
#!/bin/bash
Path=/data
backup_Server=172.16.1.41
/usr/bin/inotifywait -mrq --format '%w%f' -e create,close_write,delete /data | while read line
do
if [ -f $line ];then
rsync -az $line --delete rsync_backup@$backup_Server::nfsbackup --password-file=/etc/rsync.password
else
cd $Path &&\
rsync -az ./ --delete rsync_backup@$backup_Server::nfsbackup --password-file=/etc/rsync.password
fi
done
# 脚本可以加入开机启动
echo "/bin/sh /server/scripts/inotify.sh &" >> /etc/rc.local

4.参数优化

cat /proc/sys/fs/inotify/*
max_queued_events max_user_instances max_user_watches
echo "50000000" > /proc/sys/fs/inotify/max_user_watches
echo "326790" > /proc/sys/fs/inotify/max_queued_events

5.inotify优缺点

监控文件系统事件变化,通过同步工具实现实时数据同步;

并发如果大于200个文件(10-100k),同步就会有延迟.

6.通过start/stop控制inotify.sh脚本的启动和停止

#!/bin/bash
#chkconfig: 2345 38 46
. /etc/init.d/functions if [ $# -ne 1 ];then
usage: $0 |start|stop|
exit 1
fi case "$1" in
start)
/bin/sh /server/scripts/inotify.sh &
echo $$ > /var/run/inotify.pid
if [ `ps -ef | grep inotify | grep -v grep | wc -l` -gt 2 ];then
action "inotify service is started" /bin/true
else
action "inotify service is started" /bin/false
fi
;;
stop)
kill -9 `cat /var/run/inotify.pid` > /dev/null 2>&1
pkill inotifywait
sleep 1
if [ `ps -ef | grep inotify | grep -v grep | wc -l` -eq 0 ];then
action "inotify service is stopped" /bin/true
else
action "inotify service is stopped" /bin/false
fi
;;
*)
usage: $0 |start|stop|
exit 1
esac
chkconfig --add syncd

7.解决crontab中无法执行python脚本的问题

a.首先你得知道是环境变量问题还是你的脚本执行有报错,
像一些编码报错、没写全路径、缺少环境变量的问题,就不在这里赘述了;
b.将问题先定位到日志中
*/1 * * * * python绝对路径 脚本绝对路径 >> 日志文件绝对路径 2>&1
查看日志发现脚本被定时执行了,但日志有报错:
TERM environment variable not set.
IndexError: list index out of range
经过排查,是因为脚本中执行了os.popen('top -n 1 | awk xxx')这样的语句,
导致取数据的列表为空,对空列表取值就会报上面的错,替换相应的程序即可解决问题.

参考博客:https://www.cnblogs.com/jackyyou/p/5681126.html

参考博客:https://www.cnblogs.com/chensiqiqi/p/6542268.html