Friday, November 7, 2008

[inotify] 取得Linux filesystem的檔案異動事件

* May 10 Sat 2008 20:25
*
[inotify] 取得Linux filesystem的檔案異動事件

加入書籤: HemiDemi MyShare Baidu Google Bookmarks Yahoo! My Web Del.icio.us Digg technorati furl 加入此網頁到:YouPush 加入此網頁到:你推我報
參考網頁:

http://linux.die.net/man/7/inotify
http://edoceo.com/creo/inotify

簡易說明:

首先,linux kernel >= 2.6.13
如果是centos的話,5.1版本的應該是2.6.18(51)
如果是centos44 or 46的話,請先升級

如果系統是>=2.6.13的話,預設會支援Inotify file change notification
也就是檔案有任何異動,都會傳Event出來

然後安裝perl module => Linux::Inotify2

利用perl接收系統所傳出來的訊息
請參照以下的perl程式
http://edoceo.com/creo/inotify

裡頭會接收到mask
應該是以下的編號對應:
改天在花個時間來找找看

我覺得 Bit Description
1 IN_ACCESS File was accessed (read) (*)
2 IN_ATTRIB Metadata changed (permissions, timestamps, extended attributes, etc.) (*)
4 IN_CLOSE_WRITE File opened for writing was closed (*)
8 IN_CLOSE_NOWRITE File not opened for writing was closed (*)
16 IN_CREATE File/directory created in watched directory (*)
32 IN_DELETE File/directory deleted from watched directory (*)
64 IN_DELETE_SELF Watched file/directory was itself deleted
128 IN_MODIFY File was modified (*)
256 IN_MOVE_SELF Watched file/directory was itself moved
512 IN_MOVED_FROM File moved out of watched directory (*)
1024 IN_MOVED_TO File moved into watched directory (*)
??? IN_OPEN File was opened (*)

# 97-05-12找到一個新的方向
# 可以遞迴到底下的每一個目錄
# 搭配while,可以執行動作
# 以下是指令,-r是遞迴,-m是直接print出來,-e access可選擇各種事件
# /root當然就是目錄,因為還沒有去找怎麼樣去搭配perl去寫程式(shell script有找到)
inotifywait -r -m -e access /root

先看一下sh的範例
列出root資料夾下被存取的檔案相關訊息

#!/bin/sh
# A slightly complex but actually useful example
# 12/05/08 03:37 ACCESS /root/ 123.txt

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %e %w %f' \
-e access /root | while read date time event path file; do
echo "${date} ${time} ${event} ${path} ${file}"
done

No comments: