Skip to content

Instantly share code, notes, and snippets.

@tachoknight
Last active November 2, 2020 16:50
Show Gist options
  • Save tachoknight/14b7579a2812deda6cc955568e60a8bf to your computer and use it in GitHub Desktop.
Save tachoknight/14b7579a2812deda6cc955568e60a8bf to your computer and use it in GitHub Desktop.
This is a small script that finds unique countries in fail2ban logs. I was curious where the attacks on my servers were originating from, so I wrote this script to show me all the interesting countries that presumably have bots running ๐Ÿ˜‚
#!/bin/bash
# This script assumes you are running fail2ban (https://www.fail2ban.org)
# and have also installed the "geoiplookup" command
# Note that this script uses sudo because the fail2ban logs are typically
# root-owned
# This is an empty array that will be populated with the names
# of the countries we get from geoiplookup
COUNTRIES=()
# This array is filled with the results of the /var/log/fail2ban.log files
# where we are only interested in the IP address (last entry in the line).
# Note that we also do a tolower() because sometimes the entry will simply
# be the word "Ban", which we will test for
BANNEDIPLIST=(`sudo zgrep 'Ban' /var/log/fail2ban.log* | awk '{print $8}' | awk '{print tolower($0)}'`)
# Now for each entry in the BANNEDIPLIST array..
for i in "${BANNEDIPLIST[@]}"
do
# Skip if the entry is "ban"
if [ $i == "ban" ]; then
continue
fi
# Gets us the country. This is done by piping the output of
# geoiplookup to head -1 to get us only the first line where
# the country is identified. The cut command gets us the
# full contents of the line after the 5th column (easier to use
# than awk here)
COUNTRY=`geoiplookup -i $i | head -1 | cut -d' ' -f5-`
# It is super important to use double quotes around
# the array entries to preserve entries that have
# spaces (e.g. "United States")
COUNTRIES=("${COUNTRIES[@]}" "$COUNTRY")
done
# Now we're going to use readarray in cojunction with sort -u (which gives us unique
# values) to populate a new array, UNIQUECOUNTRIES, with the name of the country
# that the IP address is from
readarray -t UNIQUECOUNTRIES < <(for a in "${COUNTRIES[@]}"; do echo "$a"; done | sort -u)
for a in "${UNIQUECOUNTRIES[@]}"; do echo "$a"; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment