监控nginx的访问日志是否有被刷的情况

有时候网站被刷了我却不知道,所以想了个简单的办法,如下: 写个shell,每小时记录一次独立IP的访问次数到文件里

#!/bin/bash

if [ $# -ne 2 ];then
echo "Missing Operand..."
exit 1
fi

awk '{print $1,$4}' /usr/local/nginx/logs/$1 |grep 2014:`date|awk '{print $4}'|awk -F ':' '{print $1}'`|awk '{print $1}'|sort |uniq -c |sort -rn|head -$2 > /usr/local/uniqIpAccessCnt/`date +%Y-%m-%d-%H`.txt

第一个参数表示日志名,第二个参数表示想记录的独立IP数量,每小时在/usr/local/uniqIpAccessCnt/目录下生成一个文件,类似“2014-12-02-09.txt”,表示14年12月2号9点的独立IP访问情况,文件内容如下

10304 111.206.12.85
 3351 112.9.28.220
 2191 124.152.184.80
 1706 221.214.13.179
 1407 120.192.232.82
 1208 119.190.40.169
 1137 58.222.187.194
  927 122.224.148.178
  915 218.3.162.66
  899 27.13.83.173
  806 113.4.197.208
  800 114.239.129.160
  763 175.1.35.110
  720 180.89.233.72
  714 118.197.131.232
  652 221.192.232.38
  596 175.171.126.215
  509 117.174.26.117
  470 118.144.66.196
  465 218.241.217.203

再写个python监控生成的文件,我设定阈值为10000,超过就发邮件通知。

58 * * * * /usr/local/bin/get_uniq_ip_access_cnt.sh www.abc.com.log 20 
0 * * * * /usr/local/bin/malicious_access_mon.py
#!/usr/bin/python
# -*- coding: cp936 -*-

import os
import time
import datetime
import string
import email
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def SendMail():

    server = 'Web-1.2.3.4'
    mail_to = ["san.zhang@abc.com", "si.li@abc.com"]
    mail_host = "mail.abc.com"
    mail_user = "webmaster@abc.com"
    mail_pass = "passwd"
    mail_from = "webmaster@abc.com"
    mail_postfix = "abc.com"
    mail_subject = "Malicious Access - " + server +" !!!"
    mail_body = mailbody

    msg = MIMEMultipart()
    body = MIMEText(mail_body,_subtype='plain',_charset='gb2312')
    body = MIMEText(mail_body,_subtype='plain',_charset='utf-8')
    msg.attach(body)
    
    msg['Subject'] = mail_subject
    msg['From'] = mail_from
    msg['To'] = ";".join(mail_to)
    
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(mail_from, mail_to, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False  

def handlefile():

    path=r"/usr/local/uniqIpAccessCnt/"
    files=[(os.path.getmtime(path+x),path+x) for x in os.listdir(path)]
    files.sort()
    fname = files[-1][1]
    print fname

    f = open(fname, 'r')
    line = f.readline()
    cnt = (line.split('.')[0]).split(' ')[-2]
    print cnt
    if int(cnt) > 10000:
        global mailbody
        mailbody = 'Access record as follows in the last hour:\n\n\n  Count      IP\n\n' 
        lines = f.readlines()
        f.close()
        mailbody = mailbody + line
        for x in lines:
            mailbody = mailbody + x
        print mailbody
        SendMail()

def main():
    handlefile()

main()

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注