2012-08-04 187 views
2

以下bash腳本每天都會發送包含PHP錯誤日誌的電子郵件。修改bash腳本以在讀取文件時排除文本

#!/bin/bash 

# phperrlog v1.0 
# by vladimir prelovac http://www.prelovac.com/vladimir/ 
# 
# parse error logs on your server and send you daily updates to email 

# configure options 
    EMAIL="[email protected]" 

    WORKDIR="/var/scripts" 
    TAIL=50 # number of entries to send 
# IGNORE="/backup" # path to ignore 

# script starts 'ere 

cd $WORKDIR 
rm phperrlog.txt 2>/dev/null 

LIST=$(ls /var/log/apache2/*-error.log) 
today=$(date +%Y-%m-%d) 

for i in $LIST 
    do 
    if [ -f $i ]; then 
     time=$(date -r $i +%F) 
     if [ "$time" == "$today" ]; then 
     echo $i >>phperrlog.txt 
     echo "---------------------------------" >>phperrlog.txt 
     tail -n $TAIL $i >>phperrlog.txt 
     echo -e "\n\n\n\n" >>phperrlog.txt 
     fi 
    fi 
done 

    if [ -f phperrlog.txt ]; then 
    mail -s "PHPERRORLOG SCRIPT: server error logs - $today" $EMAIL < phperrlog.txt 
    fi 

我怎麼能修改此腳本,以便它排除類似這樣的所有錯誤:

[週四8月2日10點54分33秒2012] [錯誤] [客戶12.345.67.89]目錄 指數Options指令禁止: /無功/網絡/域/公/模板/ IMG/

[週四8月2日11點25分35秒2012] [錯誤] [客戶12.345.67.89]客戶端通過服務器拒絕 配置: /var/www/domain/public/templates/sidebar .tpl

我更感興趣的是:

  • PHP的通知/警告/致命錯誤
  • 文件不存在
+0

你考慮'grep的-v'? – Bernhard 2012-08-04 08:43:26

+0

備註:您可以在/ var/log/apache2/* - error.log中使用'for i而不是$ LIST來避免很多空白等問題。對於您的情況,這並不重要,但它很好養成正確處理空白的習慣。這也意味着你應該在for循環中使用「$ i」而不是簡單的$ i。 – patrix 2012-08-04 09:24:36

回答

3

grep可以從文件中讀取模式

-f file, --file=file 
     Read one or more newline separated patterns from file. Empty 
     pattern lines match every input line. Newlines are not considered 
     part of a pattern. If file is empty, nothing is matched. 

在您的情況下,您必須決定是否要使用白名單(您希望在報告中看到的模式列表)或黑名單(您列出的模式爲而不是想要查看)。一旦你已經收集到的有關模式與

grep -f /path/to/whitelist.txt "$i" | tail -n ${TAIL:-50} >> phperrlog.txt 

grep -v -f /path/to/blacklist.txt "$i" | tail -n ${TAIL:-50} >> phperrlog.txt 

更換tail -n $TAIL $i >>phperrlog.txt我可能會啓動一個黑名單,並隨着時間的推移添加其他格式時,我發現我行不希望再見。最初的黑名單可能包含

Directory index forbidden by Options directive 
client denied by server configuration 

加工您的樣品。

+0

感謝您的完美工作,僅僅出於興趣:'$ {TAIL:-50}'部分是做什麼的?我們怎麼會減50? – 2012-08-04 17:05:09

+1

如果TAIL未定義或爲空,則替換值50。我這樣做是出於習慣,以確保在未設置TAIL的情況下腳本不會失敗。 – patrix 2012-08-04 17:46:35

0

嘗試更換重定向

mail -s "PHPERRORLOG SCRIPT: server error logs - $today" $EMAIL < phperrlog.txt 

與進程和管道,例如

grep -v '\[error\]' < phperrlog.txt | mail -s "PHPERRORLOG SCRIPT: server error logs - $today" $EMAIL 

grep -v '\[error\]' phperrlog.txt | mail -s "PHPERRORLOG SCRIPT: server error logs - $today" $EMAIL