Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
else:
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:
break
else:
data = parse(line)
ONEWEEKAGO = datetime.datetime.now() - 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:
bannedRemoteIp.append(data["remote_ip"])
bannedRemoteIpCounter.append(0)
bannedRemoteIpCounter[bannedRemoteIp.index(data["remote_ip"])] += 1
print("------------------------------------------------------")
print("Server attack statistics for the SSH service")
print()
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)
print("------------------------------------------------------")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment