2012-08-04 144 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