我想監視我的 Linux debian 機器上的記錄檔 (syslog)。因此,如果有一個帶有特定字串的新條目,我想執行一個腳本。
字串是“警報開始”和“警報結束”
所以它應該看起來像這樣(沒有程式語言,只是我的俚語;-)):
if logfile has changed
get last line (or all new lines)
search for string
if string = "alarm start" found then /foo/bar/script_alarm_start.sh
if string = "alarm end" found then /foo/bar/script_alarm_end.sh
我可以使用類似守護程式的東西嗎?
日誌檔如下所示:
Jul 7 06:38:17 zma_m1[8075]: INF [DoorCam: 898051 - Opening new event 14, alarm start]
Jul 7 06:38:23 zma_m1[8075]: INF [DoorCam: 898056 - Gone into alert state]
Jul 7 06:38:31 zmc_m1[8047]: INF [DoorCam: 900000 - Capturing at 25.00 fps]
Jul 7 06:38:33 zma_m1[8075]: INF [DoorCam: 898116 - Left alarm state (14) - 125(5) images]
Jul 7 06:38:33 zma_m1[8075]: INF [DoorCam: 898116 - Closing event 14, alarm end]
...
Jul 7 06:40:38 zma_m1[8075]: INF [DoorCam: 901286 - Opening new event 15, alarm start]
Jul 7 06:40:44 zma_m1[8075]: INF [DoorCam: 901289 - Gone into alert state]
Jul 7 06:40:53 zma_m1[8075]: INF [DoorCam: 901349 - Left alarm state (15) - 123(3) images]
Jul 7 06:40:53 zma_m1[8075]: INF [DoorCam: 901349 - Closing event 15, alarm end]
乾杯!
答案1
嘗試這個:
#!/bin/bash
function fs { ls -l LOGFILE | awk '{print $5}' }
function lc { wc -l LOGFILE | awk '{print $1}' }
function sv { fileSize=$(fs) fileLength=$(lc) }
function ov { nFileSize=$(fs) nFileLeng=$(fs) }
sv
while true; do
ov
if [[ $nFileSize != $fileSize ]]; then
newLines=$(tail -n $(($nFileLeng-$fileLength)))
if [[ $(echo "$newLines" | grep "alarm start") ]]; then
/foo/bar/script_alarm_start.sh
elif [[ $(echo "$newLines" | grep "alarm end") ]]; then
/foo/bar/script_alarm_end.sh
fi
fi
sv
done
將 LOGFILE 變更為日誌檔案的位置