Update autoban.py

This commit is contained in:
mengskysama 2018-02-19 02:24:42 +08:00 committed by GitHub
parent a7a60e3452
commit 385d89cd69
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -25,9 +25,17 @@ from __future__ import absolute_import, division, print_function, \
with_statement with_statement
import sys import sys
import socket
import argparse import argparse
import subprocess import subprocess
def inet_pton(str_ip):
try:
return socket.inet_pton(socket.AF_INET, str_ip)
except socket.error:
return None
if __name__ == '__main__': if __name__ == '__main__':
parser = argparse.ArgumentParser(description='See README') parser = argparse.ArgumentParser(description='See README')
parser.add_argument('-c', '--count', default=3, type=int, parser.add_argument('-c', '--count', default=3, type=int,
@ -37,17 +45,21 @@ if __name__ == '__main__':
ips = {} ips = {}
banned = set() banned = set()
for line in sys.stdin: for line in sys.stdin:
if 'can not parse header when' in line: if 'can not parse header when' not in line:
ip = line.split()[-1].split(':')[-2] continue
ip_str = line.split()[-1].rsplit(':', 1)[0]
ip = inet_pton(ip_str)
if ip is None:
continue
if ip not in ips: if ip not in ips:
ips[ip] = 1 ips[ip] = 1
print(ip)
sys.stdout.flush() sys.stdout.flush()
else: else:
ips[ip] += 1 ips[ip] += 1
if ip not in banned and ips[ip] >= config.count: if ip not in banned and ips[ip] >= config.count:
banned.add(ip) banned.add(ip)
cmd = ['iptables', '-A', 'INPUT', '-s', ip, '-j', 'DROP'] print('ban ip %s' % ip_str)
cmd = ['iptables', '-A', 'INPUT', '-s', ip_str, '-j', 'DROP', '-m', 'comment', '--comment', 'autoban']
print(' '.join(cmd), file=sys.stderr) print(' '.join(cmd), file=sys.stderr)
sys.stderr.flush() sys.stderr.flush()
subprocess.call(cmd) subprocess.call(cmd)