Created
June 25, 2024 23:35
-
-
Save cfultz/b7000152ba2c2d70a0a43fdd389feb7d to your computer and use it in GitHub Desktop.
Fail2Ban Parse (original by classmember, spelling corrections and print correction by me: https://gist.github.com/classmember/a100c2bfe9936daf4ceff24743f871ab)
This file contains hidden or 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
| #!/usr/bin/env python | |
| ''' | |
| Parse fail2ban log for IP addresses | |
| Usage: $ ./parse.py log | |
| ''' | |
| import re | |
| import sys | |
| import subprocess | |
| import collections | |
| MAX_OCCURRENCES = 600 # IPs are banned after this many occurrences in log. | |
| LOG_FILE = '/var/log/fail2ban.log' | |
| def main(target_file): | |
| ''' | |
| Parse fail2ban log for IP addresses | |
| :param: target_file - fail2ban file to search for IPs in. | |
| ''' | |
| ip_regex = (r'\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.' | |
| r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.' | |
| r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.' | |
| r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b') | |
| all_matches = [] | |
| # find matches and add them to array all_matches | |
| with open(target_file) as log: | |
| for line in log: | |
| match = re.search(ip_regex, line) | |
| if match: | |
| all_matches.append(match.group()) | |
| # get all IPs with matches equal or greater than the amount MAX_OCCURRENCES | |
| sorted_ips = collections.Counter(all_matches) | |
| banned_ips = [item for item in sorted_ips if sorted_ips[item]>MAX_OCCURRENCES] | |
| for ip in banned_ips: | |
| print ('Banned ', ip) | |
| subprocess.Popen(["iptables", "-A", "INPUT", "-s", ip, "-j", "DROP"]) | |
| if __name__ == '__main__': | |
| main(LOG_FILE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment