Skip to content

Instantly share code, notes, and snippets.

@adimania
Created November 6, 2014 17:53
Show Gist options
  • Save adimania/50b88e84d8195b2d9f10 to your computer and use it in GitHub Desktop.
Save adimania/50b88e84d8195b2d9f10 to your computer and use it in GitHub Desktop.
Script to block annoying IPs
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
@amitu
Copy link

amitu commented Nov 7, 2014

Use tempfile.mkstemp instead of random.choice. Also use collections.defaultdict to simplify things a bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment