需求:因nginx作了防刷機制以後, error.log 會出現ip刷服務器,也被nginx擋掉了,並無具體刷到後端服務器,但error.log屢次出現ip,現計劃把出現5次以上的ip寫入黑名單。python
nginx log日誌格式:nginx
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"shell
寫入黑名單文件:後端
[root@ ~]# more /mnt/nginx/conf/refuseip.conf api
deny 111.164.58.3;服務器
注:以上日誌格式正確,ip和連接有篡改過,沒法直接訪問。app
#!/usr/bin/pythonide
# -*- coding:UTF-8 -*-ui
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()