Sam's Tech Blog

'You can check out any time you like, But you can never leave!'

2020-01-11

fail2ban

fail2ban top100 ban script

fail2ban

#!/bin/bash
# SamTzu - 2020-01
# https://sami.mattila.eu/tech/
# This script will read top 100 offender IP's from fail2ban log and (permanently) ban them (untill you reboot)!
# How to list banned IP's
# iptables --list
# You can unban any ip address using iptables
# iptables -D INPUT -p all -s IP.ADDRESS.HERE -j DROP

# Create or sync ban-list
touch /root/fail2ban-top100-list.txt
chmod +x /root/fail2ban-top100-list.txt
# Alternatively you can use RSYNC to copy common ban list over the network
# rsync -a MY.SYNC-SERVER.COM:/root/fail2ban-top100-list.txt /root/fail2ban-top100-list.txt
# Or you could append lists from 10 servers and create fail2ban-top1000-list.txt
# cat /root/fail2ban-top100-list.txt | ssh root@MY.SYNC-SERVER.COM -T "cat >> /root/fail2ban-top1000-list.txt"

# Read your servers fail2ban.log and export top100 offenders to list
zgrep -h "Ban " /var/log/fail2ban.log* | awk '{print $NF}' | sort | uniq -c | sort -n | tail -100  > /root/fail2ban-top100-list.txt

# Uncomment next line to see the top-100 list
# zgrep -h "Ban " /var/log/fail2ban.log* | awk '{print $NF}' | sort | uniq -c | sort -n | tail -100
# Uncomment next line to only see IP's without the number of offences.
# zgrep -h "Ban " /var/log/fail2ban.log* | awk '{print $NF}' | sort | uniq -c | sort -n | tail -100 | awk '{print $2}'

# Read the top100 list and ban them permanently
for IP in $(cat /root/fail2ban-top100-list.txt); do iptables -A INPUT -s $IP/32 -d 0/0 -j DROP; done