Bash script to bulk-ban IP addresses found by WordFence (using csf, geoiplookup)


We currently use the excellent WordFence plugin on almost all of the WordPress installations we host. Once a week or so, WordFence will email a list of IP addresses it’s detected that are attacking a given site — i.e. they’re trying to brute-force something on the server, guess passwords, take advantage of possible software vulnerabilities. Rather than block each of these individually using csf (not hard to do, but a chore with many IPs), I finally created this simple bash script that allows me to copy and paste the list of offending IPs into the command line, hit enter twice to initiate processing, and then it automatically bans every valid IP address it finds.

Feel free to use this yourself if it seems helpful! 🙂

ban_ips.sh

#!/bin/bash
# Script to bulk ban bad IPs that are copy/pasted

printf "Give me some IPs to ban using CSF!  Use ctrl-d to cancel, or new line to process.  \n"

ip_list=$(sed '/^$/q')

echo "Processing..."

echo "$ip_list" | while read -r line;
do
  ip="$(grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' < << "$line")"
  if [[ ! -z $ip ]]
    then
      geoip=`geoiplookup $ip`
      echo "Found IP $ip"
      echo "$geoip"
      echo "Banning IP..."
      csf -d $ip "Bulk banning IPs found by WordFence ($(tr '\n' ' ' <<< $geoip))"
  fi
done

echo "Done!"

You can checkout this script and the others I've written / shared here: https://github.com/gserafini/useful-server-scripts/tree/master/scripts

, ,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

sell diamonds