Skip to content

Instantly share code, notes, and snippets.

@mplinuxgeek
Last active August 23, 2018 01:14
Show Gist options
  • Save mplinuxgeek/4727e763de808a1588a4f9abb204aab7 to your computer and use it in GitHub Desktop.
Save mplinuxgeek/4727e763de808a1588a4f9abb204aab7 to your computer and use it in GitHub Desktop.
Generate a report of failed login IP's, which country they originate from and the count of each IP. These are generally ssh brute force attempts, I use the report to add new IP's that are brute forcing me to a blocklist on my firewall.
#!/bin/bash
LASTB=$(lastb | awk '{print $3}' | grep -v "192.168.1" | head -n -2 | sort | uniq -c | sed -e 's/^[ \t]*//' | sort -k1nr)
# lastb returns failed login attempts
# print only the 3rd column which has the IP addresses
# grep out local network entries
# remove last 2 lines of the output, lasst line is the date and 2nd last is blank
# sort list for uniq
# uniq -c displays a count of the uniq entries
# remove the leading spaces
# sorts the output using the 1st column from largest to smallest
printf "%s\t%s\t%s\n" "IP" "Country" "Count"
echo "${LASTB}" | while read line; do
# The 2 lines below use parameter expansion, see http://wiki.bash-hackers.org/syntax/pe#substring_removal
# Returns the IP address being the longest part of the string
IP=${line##* }
# Returns the number of instances the IP address appeared in lastb
COUNT=${line% *}
# Greps the output of whois for the country the IP originates from
COUNTRY=$(whois ${IP} | grep -i country | awk '{print $2}' | head -n 1)
# Print the output in a nice format
printf "%s\t%s\t%d\n" ${IP} ${COUNTRY^^} ${COUNT}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment