监控日志脚本:

#!/bin/bash
#---------------------------------
#           监控日志脚本
#---------------------------------

export SITENAME=`hostname` # 名称,用于区分报警名称
export LOGFILE='/etc/ocserv/login.log' # 要监控的日志
export SHELLLOG="/root/bin/monitor.log" # 脚本运行日志
export BEFORELINENUM=`sed -n '$=' $LOGFILE` # 开始读取的行
export SECONDSPAN=5 # 每次循环间隔的时间,秒
export T1=`date '+%Y-%m-%d %H:%M:%S'` # 时间
export MONITOR_STRING='connect' # 要监控的字符串
export ACCESS_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # dingding的token


function snedmsg {
    CONTENT=$1
    curl "https://oapi.dingtalk.com/robot/send?access_token=$ACCESS_TOKEN" \
    -H 'Content-Type: application/json' \
    -d "{\"msgtype\": \"text\",\"text\": {\"content\": \"${CONTENT}\" }}"
    echo -e
}


echo "$T1 $SITENAME 开始监听 $LOGFILE, $BEFORELINENUM" >> $SHELLLOG
while true
do
    afterlinenum=`sed -n '$=' $LOGFILE`
    #当日志文件清空时重置起始点,通常日志会换天写文件
    if [ $afterlinenum -lt $BEFORELINENUM ];then
        BEFORELINENUM=0
    fi
    line=$(( $afterlinenum - $BEFORELINENUM ))
    #echo " line:"$line >> $SHELLLOG
    BEFORELINENUM=$afterlinenum
    content=`tail -n $line $LOGFILE | grep -A 20 $MONITOR_STRING`
    if [ -n "$content" ]; then
        T1=`date '+%Y-%m-%d %H:%M:%S'`
        IP=`hostname -I | awk '{print $1}'`
#        IPs=`echo "$content" | grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | uniq | tr "\r\n" ","`
#        Location=`curl 192.168.199.74/getiplocation.php?ip=$IPs`
#        msg="Time: $T1\nHostname: $SITENAME\nNumber: $line\nIP: $IP\nContent: $content\nLocation: $Location"
        msg="Time: $T1\nHostname: $SITENAME\nNumber: $line\nIP: $IP\nContent: $content"
        echo -e $msg >> $SHELLLOG
        echo -e "匹配到相应的字符串,准备发送告警" >> $SHELLLOG
        snedmsg "$msg"
        echo "发送完成..." >> $SHELLLOG
    fi
    sleep $SECONDSPAN
done

echo "程序退出." >> $SHELLLOG
exit