Created
November 6, 2014 17:53
-
-
Save adimania/50b88e84d8195b2d9f10 to your computer and use it in GitHub Desktop.
Script to block annoying IPs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import subprocess | |
import random | |
import string | |
BAD_THRESHOLD = 5 # If there are more than these failed attempt then IP will be blocked | |
iptables_str = "/sbin/iptables -I INPUT -s IP-HERE -j DROP\n" | |
identifier = ''.join(random.choice(string.lowercase) for i in range(6)) | |
script = open("/tmp/iptables.sh-" + identifier,"w") | |
def is_valid_ip(ip): | |
try: | |
socket.inet_aton(ip) | |
return True | |
except socket.error: | |
return False | |
ip_dict={} | |
with open("/var/log/secure") as logf: | |
for line in logf: | |
if "sshd" in line and "preauth" in line: | |
ip = line.split()[-2] | |
if is_valid_ip(ip): | |
if ip in ip_dict: | |
ip_dict[ip] += 1 | |
else: | |
ip_dict[ip] = 1 | |
for ip in ip_dict: | |
if ip_dict[ip] > BAD_THRESHOLD: | |
script.write(iptables_str.replace("IP-HERE", ip)) | |
script.close() | |
print "Please examine and execute /tmp/iptables.sh-" + identifier |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use tempfile.mkstemp instead of random.choice. Also use collections.defaultdict to simplify things a bit.