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! 🙂

# 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;
  ip="$(grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' < << "$line")"
  if [[ ! -z $ip ]]
      geoip=`geoiplookup $ip`
      echo "Found IP $ip"
      echo "$geoip"
      echo "Banning IP..."
      csf -d $ip "Bulk banning IPs found by WordFence ($(tr '\n' ' ' <<< $geoip))"

echo "Done!"

You can checkout this script and the others I've written / shared here:

, ,

Leave a Reply

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

sell diamonds