Skip to content

Instantly share code, notes, and snippets.

@mmaridev
Created October 12, 2018 20:49
Show Gist options
  • Save mmaridev/03f1b638e10ff40ca3fbaf734b2cd285 to your computer and use it in GitHub Desktop.
Save mmaridev/03f1b638e10ff40ca3fbaf734b2cd285 to your computer and use it in GitHub Desktop.
Python 3 script to update an ipset blacklist from postfix's log
#!/usr/bin/python3
import os
import ipaddress
import sys
DRY_RUN = "--dry-run" in sys.argv
def is_valid_ip(address):
try:
ipaddress.ip_address(address)
return True
except:
pass
return False
ips = [ a for a in os.popen("grep warning /var/log/mail.info | grep 'authentication failed' | cut -d '[' -f 3 | cut -d ']' -f 1").read().split("\n") if is_valid_ip(a) ]
send_to_blacklist = []
for ip in ips:
if ip not in send_to_blacklist:
# Check if the ip occurs more than tree times
if ips.count(ip) >= 3:
# Send to blacklist
send_to_blacklist.append(ip)
# Parse actual blacklist from ipset
blacklisted_ips = [ a for a in os.popen("ipset list blacklist").read().split("\n") if is_valid_ip(a) ]
# Send to blacklist unblacklisted ips
for ip in send_to_blacklist:
if ip not in blacklisted_ips:
if not DRY_RUN:
os.popen("ipset add blacklist %s" % ip)
print("Added to blacklist", ip)
if DRY_RUN:
sys.exit(0)
# Send the new complete blacklist to the file
blacklisted_ips = [ a for a in os.popen("ipset list blacklist").read().split("\n") if is_valid_ip(a) ]
a = open("/etc/blacklist.ip", "w")
for ip in blacklisted_ips:
a.write(ip)
a.write("\n")
a.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment