FastNetMon

Wednesday, 17 March 2010

Пример Python скрипта защиты от DoS / DDoS атак посредством анализа логов


#!/usr/bin/python
# -*- coding: utf-8 -*-

import tailer
import re
import os

ips = {}

for line in tailer.follow(open('/var/log/nginx/access.log')):
m = re.match('^(\d+.\d+.\d+.\d+).*?- 400 0 "-" "-" "-" 0.000--$', line)

if m:
print "Blank DoS request: %s" % line

ip = m.group(1)

print "ban ip: %s" % ip
os.system("ban_ip.sh %s" % ip)

m_bot = re.match("^(\d+.\d+.\d+.\d+).*?GET /someurl/ .*?$", line)

if m_bot:
ip = m_bot.group(1)


if ips.has_key(ip):
ips[ip] = ips[ip] + 1

if ips[ip] > 100:
print "ban ip %s" % ip
os.system("ban_ip.sh %s" % ip)
else:
ips[ip] = 0



print "Bot detected request %s ip: %s" % ( ips[ip], ip )
print line



В данном случае после 100 запросов к someurl бот будет забанен.

No comments :

Post a Comment

Note: only a member of this blog may post a comment.