Skip to content

Instantly share code, notes, and snippets.

@haseebr
Last active August 29, 2015 14:12
Show Gist options
  • Save haseebr/6735ab0d12a6c624f942 to your computer and use it in GitHub Desktop.
Save haseebr/6735ab0d12a6c624f942 to your computer and use it in GitHub Desktop.
#1/usr/bin/python
from subprocess import call, check_output
import re
import cStringIO
regex = '\s*(\d*)\s(.*)'
ip = check_output('/bin/netstat -ntu | awk \'{print $5}\' | cut -d: -f1 | sort | uniq -c | sort -n', shell = True)
time = str(check_output('date'))
with open('last_run', 'wb') as f:
f.write('bl.py last ran at {}\n'.format(time.strip()))
for line in ip.split('\n'):#.readlines():
if re.search(regex, line):
access = re.search(regex, line).groups()
if int(access[0]) > 100:
if str(access[1]) in str(check_output('/sbin/iptables -L -v -n', shell = True)):
print access[1],' is already blacklisted'
pass
else:
callment = '/sbin/iptables -A INPUT -s {} -j DROP\n'.format(access[1])
call(callment, shell = True)
call('/usr/sbin/service php5-fpm restart', shell = True)
statement = 'ip {} was blocked at {}. It had {} simultaneous connections.\n'.format(access[1].strip(), time.strip(), access[0])# + callment
print statement
with open('blocked', 'ab') as f:
f.write(statement)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment