ufw script to barring of specific IP PDF Print E-mail
Written by Carl Friis-Hansen   
Sunday, 30 November 2008 13:33

I frequently find an IP address to be very malicious and therefore a candidate for being blocked by the ufw on the server. For this purpose I find it easiest to use the file /var/lib/ufw/user.rules directly. Also, a search for an already incorporated barring of the particular IP has to be exercised before the new rule is inserted. This was the reason I wrote a small, simple script to do the whole job. The script is called add-bad-ip and it's only parameter is the IP to be blocked:

sudo add-bad-ip 111.122.133.144

The script:

add-bad-ip
#!/bin/sh
 
if [ "$1" = "--help" ] || [ "$1" = "-h" ] || [ -z "$1" ]; then
  echo "\nBan all access from a specific IP address using ufw/iptables"
  echo "Should be run with sudo prefix\n"
  echo "Usage:"
  echo "  $0 IP-ADDRESS"
  echo "  $0 --help | -h\n"
  echo "Exit values:"
  echo "  0    IP added and blocked in user.rules."
  echo "  1    IP already exists in user.rules"
  echo "  2    $0 invoked with -h or --help parameter"
  echo ""
  exit 2
fi
 
if grep $1 /var/lib/ufw/user.rules > /dev/null; then
  echo "\n$1 already exists in user.rules\n"
  exit 1
else
  echo "\n$1 was not found and will be added"
  # Add bad IP address
 
#  ### RULES ###
#
#  ### tuple ### deny any any 0.0.0.0/0 any 59.109.75.37
#  -A ufw-user-input -s 59.109.75.37 -j DROP
 
  OLD="### RULES ###"
  NEW="### RULES ###\n\n### tuple ### deny any any 0.0.0.0\/0 any $1\n-A ufw-user-input -s $1 -j DROP"
  sed -i "s/$OLD/$NEW/" /var/lib/ufw/user.rules
  echo "ufw disable"
  ufw disable
  echo "ufw enable"
  ufw enable
  echo "...done\n"
  exit 0
fi

 


 

Last Updated on Thursday, 11 February 2010 23:50
 

Add comment

To be able to vote and have easier access to write comments, etc., go to Login and register yourself.
Your user name and email will never leave this website.


Security code
Refresh