1. 程式人生 > >inotify+rsync實現實時同步(附解決crontab中無法執行python指令碼的問題)

inotify+rsync實現實時同步(附解決crontab中無法執行python指令碼的問題)

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 [email protected]::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 
[email protected]
$backup_Server::nfsbackup --password-file=/etc/rsync.password else cd $Path &&\ rsync -az ./ --delete [email protected]$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/chensiqiqi/p/6542268.html