Skip to content

Instantly share code, notes, and snippets.

Created March 14, 2017 21:47
Show Gist options
  • Save philippmayrth/9f5b140e3f9dfe56eeaabe09d3e59a3b to your computer and use it in GitHub Desktop.
Save philippmayrth/9f5b140e3f9dfe56eeaabe09d3e59a3b to your computer and use it in GitHub Desktop.
import os
import datetime
import subprocess
FailToBanLog = "/var/log/"
# line format is
# 1995-01-01 00:00:00,000 fail2ban.server [1142]: INFO rollover performed on /var/log/fail2ban.log
# 1995-01-01 00:00:00,000 fail2ban.actions [1142]: NOTICE [sshd] Ban XXX.XX.XXX.XX
# 1995-01-01 00:00:00,000 fail2ban.filter [1142]: INFO [sshd] Found XXX.XX.XXX.XX
def parse(line):
data_1, data_2 = line.split(" ")
date_string, fail2ban_type = data_1.split(" fail2ban.")
if fail2ban_type == "actions":
data_2 = " ".join(data_2.split())
unknown_1, label, service, action, remote_ip = data_2.split()
service = service.replace("[", "").replace("]", "")
date = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S,%f")
return {
"remote_ip": remote_ip,
"service": service,
"action": action,
"date": date
return None
bannedRemoteIp = []
bannedRemoteIpCounter = []
filesInLogDir = os.listdir(FailToBanLog)
for file in filesInLogDir:
if "fail2ban.log" in file and ".gz" not in file:
with open(FailToBanLog+file, "r") as f:
while True:
line = f.readline()
if not line:
data = parse(line)
ONEWEEKAGO = - datetime.timedelta(days=7)
# use only data no older than one week
if data != None and data["action"] == "Ban" and data["date"] >= ONEWEEKAGO:
if data["remote_ip"] not in bannedRemoteIp:
bannedRemoteIpCounter[bannedRemoteIp.index(data["remote_ip"])] += 1
print("Server attack statistics for the SSH service")
print("Count, IP, Country")
for ip, count in zip(bannedRemoteIp, bannedRemoteIpCounter):
geoiplookup = subprocess.Popen(["geoiplookup", ip], stdout=subprocess.PIPE).communicate()[0]
geoiplookup = geoiplookup.decode('utf-8').replace("GeoIP Country Edition: ", "").replace("\n", "")
print(str(count).ljust(4)+" "+ip.ljust(15)+" "+ geoiplookup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment