用inotifywait監(jiān)視文件變化并執(zhí)行相應(yīng)腳本

Inotify 是一個 Linux特性,它監(jiān)控文件系統(tǒng)操作,比如讀取、寫入和創(chuàng)建。Inotify 反應(yīng)靈敏,用法非常簡單,并且比 cron 任務(wù)的繁忙輪詢高效得多。在內(nèi)核 2.6.13 以上都可以使用。

Inotify一種強(qiáng)大的、細(xì)粒度的、異步文件系統(tǒng)監(jiān)控機(jī)制,它滿足各種各樣的文件監(jiān)控需要,可以監(jiān)控文件系統(tǒng)的訪問屬性、讀寫屬性、權(quán)限屬性、刪除創(chuàng)建、移動等操作,也就是可以監(jiān)控文件發(fā)生的一切變化。

inotify-tools是一個C庫和一組命令行的工作提供Linux下inotify的簡單接口。inotify-tools安裝后會得到inotifywait和inotifywatch這兩條命令:

一是 inotifywait,它是用來監(jiān)控文件或目錄的變化,二是inotifywatch,它是用來統(tǒng)計文件系統(tǒng)訪問的次數(shù)。

我家里安裝了一個網(wǎng)絡(luò)攝像機(jī),用來監(jiān)控家里的的入口是否有異常,如果有異常就會自動錄像。錄像文件存放在nas服務(wù)器上,為了把文件做備份,我又把錄像文件定時復(fù)制到遠(yuǎn)程云服務(wù)器上。之前是采用定時備份的模式,實時性不好。為了保證備份的實時性,我查找了linux對文件的監(jiān)控功能的資料,終于發(fā)現(xiàn)了inotify-tools這個工具。通過對inotify-tools的資料的學(xué)習(xí),編寫了一個自動執(zhí)行腳本,當(dāng)檢測到攝像頭保存視頻的文件夾有變動,就自動用rsync把更改的文件同步到遠(yuǎn)程云服務(wù)器上。

下面就是安裝和使用步驟:

1. 安裝inotify-tools

家里的服務(wù)安裝的是debian 10系統(tǒng),是可以直接安裝inotify-tools工具的

#apt update
#apt install inotify-tools

就是這么簡單,看網(wǎng)上很多文章都寫的是從github下載.gz文件,然后解壓縮,再&……%&*&……,其實完全不用這么麻煩,就只需要上面兩行命令就完成了。

然后執(zhí)行inotifywatch --help,有輸出命令說明就表明工具安裝正常,可以使用了。

#inotifywatch --help
inotifywatch 3.14
Gather filesystem usage statistics using inotify.
Usage: inotifywatch [ options ] file1 [ file2 ] [ ... ]
Options:
        -h|--help       Show this help text.
        -v|--verbose    Be verbose.
        @<file>         Exclude the specified file from being watched.
        --fromfile <file>
                Read files to watch from <file> or `-' for stdin.
        --exclude <pattern>
                Exclude all events on files matching the extended regular
                expression <pattern>.
        --excludei <pattern>
                Like --exclude but case insensitive.
        -z|--zero
                In the final table of results, output rows and columns even
                if they consist only of zeros (the default is to not output
                these rows and columns).
        -r|--recursive  Watch directories recursively.
        -t|--timeout <seconds>
                Listen only for specified amount of time in seconds; if
                omitted or 0, inotifywatch will execute until receiving an
                interrupt signal.
        -e|--event <event1> [ -e|--event <event2> ... ]
                Listen for specific event(s).  If omitted, all events are 
                listened for.
        -a|--ascending <event>
                Sort ascending by a particular event, or `total'.
        -d|--descending <event>
                Sort descending by a particular event, or `total'.

Exit status:
        0  -  Exited normally.
        1  -  Some error occurred.

Events:
        access          file or directory contents were read
        modify          file or directory contents were written
        attrib          file or directory attributes changed
        close_write     file or directory closed, after being opened in
                        writable mode
        close_nowrite   file or directory closed, after being opened in
                        read-only mode
        close           file or directory closed, regardless of read/write mode
        open            file or directory opened
        moved_to        file or directory moved to watched directory
        moved_from      file or directory moved from watched directory
        move            file or directory moved to or from watched directory
        create          file or directory created within watched directory
        delete          file or directory deleted within watched directory
        delete_self     file or directory was deleted
        unmount         file system containing file or directory unmounted

2. inotifywait使用

這里直接給出我的腳本代碼,再做一個說明吧!

#!/bin/bash
dir=/ipcam                #指定需要監(jiān)視的文件夾
log_file=/watch.log   #指定輸出信息的文件,方便后面查看
rsync_file=/xxx.sh    #發(fā)現(xiàn)文件有變化時需要執(zhí)行的腳本文件
while
inotifywait -r $dir -o $log_file -e close \       #這里只監(jiān)視文件的close動作
--timefmt '%d/%m/%y %H:%M' --format '%T %w %f %e';
do  
         bash $rsync_file        #執(zhí)行同步文件的腳本
         sleep 10m               #等待10分鐘,如果不加這個命令,同步會非常頻繁,沒必要
done

剛開始的時候因為不清楚inotifywait的執(zhí)行機(jī)制,代碼寫的太復(fù)雜,反而出現(xiàn)問題,后來反復(fù)測試發(fā)現(xiàn)可以簡化,就去掉了很多不必要的命令,這樣流程也很清楚。
我的rsync腳本文件就是用rsync命令把視頻文件同步到云服務(wù)器上,大家自行查找rsync的相關(guān)資料,這里就不再累述。

3. inotifywatch的使用

inofitywatch是用來監(jiān)控文件或文件夾的變化,并輸出統(tǒng)計信息的。
比如:

# inotifywatch /ipcam -t 300 
Establishing watches...
Finished establishing watches, now collecting statistics.
total  access  close_nowrite  open  filename
51     25      13             13    /ipcam/

這里監(jiān)控了5分鐘時間,總共出現(xiàn)了51次文件變更,其中access 25次,close_nowrite 13次,open 13次,結(jié)果清晰明了。

4. 最后,也是最重要的一點,設(shè)置開機(jī)啟動腳本

#crontab -e

然后添加下面一行

@reboot /xxx/xxx.sh

Perfact!
當(dāng)然inotifywait和inotifywatch還有很多參數(shù)可以設(shè)置,功能也很強(qiáng)大,這里我只用了冰山一角就完成了我的任務(wù)。很好,很強(qiáng)大!!
置于inotify-tools的資料,可以自己找“男人”問問!

image.png

#man inotifywait

這個是最權(quán)威的資料,前提是你喜歡english,當(dāng)然現(xiàn)在網(wǎng)絡(luò)上也有成堆的中文解釋和說明可以閱讀,就看個人習(xí)慣吧!
最后,慶祝下我這篇簡書處女作的誕生??!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容