修改bash脚本以在读取文件时排除文本

时间:2012-08-04 07:51:57

标签: bash

以下bash脚本每天都会发送一封包含PHP错误日志的电子邮件。

#!/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="tech@domain.com"

  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

如何修改此脚本以排除与此类似的所有错误:

  

[Thu Aug 02 10:54:33 2012] [错误] [client 12.345.67.89]目录   Options指令禁止的索引:   /无功/网络/域/公共/模板/ IMG /

     

[Thu Aug 02 11:25:35 2012] [错误] [客户端12.345.67.89]客户端被拒绝   按服务器配置:   /var/www/domain/public/templates/sidebar.tpl

我对以下内容更感兴趣:

  • PHP通知/警告/致命错误
  • 文件不存在

2 个答案:

答案 0 :(得分: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.

在您的情况下,您必须决定是否要使用白名单(您希望在报告中看到的模式列表)或黑名单( 想要查看的模式列表) 。收集相关模式后,将tail -n $TAIL $i >>phperrlog.txt替换为

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

我可能会从黑名单开始,随着时间的推移添加其他模式,当我注意到我不想再看到的行时。最初的黑名单可以包含

Directory index forbidden by Options directive
client denied by server configuration

制作样品。

答案 1 :(得分: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