需求:因nginx做了防刷机制之后, error.log 会出现ip刷服务器,也被nginx挡掉了,并没有具体刷到后端服务器,但error.log多次出现ip,现计划把出现5次以上的ip写入黑名单。
nginx log日志格式:
2016/09/05 01:11:07 [info] 1354#0: *11981355139 limiting connections by zone "limit", client: 111.164.58.3, server: api.test.cn, request: "GET /test/test?_at=28&_av=103&_avn=1.1.2&_c=%E4%B8%8A%E6%B5%B7&_i=a4fe3bb262c171054f7ca01d8af58337&_la=0&_lo=0&_pm=iPhone&_pv=9.33.2&_pvt=2&_s=2&_sg=FF4C1556E48DBDD8A2&_sh=1136&_sw=6540&_uuid=a4fe3bb262c171054f7c55a01d8af58337&m=2791763&mid=48&pi=1&ps=10&t=1&t2=6Af95DlK55RkmekO-7W8HiTQZysThxEVOE HTTP/1.0", host: "api.test.cn"
写入黑名单文件:
[root@ ~]# more /mnt/nginx/conf/refuseip.conf
deny 111.164.58.3;
注:以上日志格式正确,ip和链接有篡改过,无法直接访问。
#!/usr/bin/python
# -*- coding:UTF-8 -*-
import subprocess
import os
IP = ("tail -f /mnt/log/nginx/error.log")
file="/mnt/nginx/conf/refuseip.conf"
child= subprocess.Popen(IP,shell=True,stdout=subprocess.PIPE)
flag=[]
while True:
line = child.stdout.readline()
if line.find("limit") != -1:
j = line.split()[11].split(",")[0]
flag.append(j)
delete=flag[-1]
num=flag.count(delete)
if num>=5:
for i in range(num):
index=flag.index(delete)
del flag[index]
print flag
f=open(file,‘a‘)
f.write("deny " +delete+";"+‘\n‘)
f.close()
本文出自 “濛sir的积累” 博客,请务必保留此出处http://mengsir.blog.51cto.com/2992083/1846937
原文地址:http://mengsir.blog.51cto.com/2992083/1846937