#!/bin/bash
# Set the log file path
LOGFILE=/var/log/syslog
# Set the time period in minutes
PERIOD=5
# Set the error count threshold
THRESHOLD=50
# Scan the log file for the past $PERIOD minutes and count errors for each IP
grep "`date --date="$PERIOD minutes ago" "+%b %_d %H:%M"`" $LOGFILE | awk '/error/{print $4}' | sort | uniq -c > /tmp/errors.log
# Send an alert for any IP that has more than $THRESHOLD errors in the past $PERIOD minutes
while read line
do
count=`echo $line | awk '{print $1}'`
if [ $count -ge $THRESHOLD ]
then
ip=`echo $line | awk '{print $2}'`
echo "Too many errors from $ip, count=$count" | mail -s "Error Alert!" admin@example.com
fi
done < /tmp/errors.log
说明: 以上脚本可以扫描指定日志文件中过去一段时间内(默认为5分钟)每个IP的错误数量,并当某个IP的错误数量超过设定的阈值(默认为50)时发送警报邮件到指定的管理员邮箱。该脚本通过grep与awk命令实现日志提取以及数量的统计,并保存在临时文件里,最后通过循环语句遍历临时文件中的信息,判断是否有IP达到设定的阈值。如果有则发送警报邮件。