Iptables block ip address – Security Shell Script

by on December 20, 2008 · 9 comments

Create /root/iptables/blocked.ips file as follows with list of ips and subnets to block entering your dedicated server:

192.168.1.0/24
202.54.1.2
# spam
202.5.1.2

Call following script from your existing shell script:

  1. #!/bin/bash
  2. # Simple iptables IP/subnet block script
  3. # -------------------------------------------------------------------------
  4. # Copyright (c) 2004 nixCraft project <http://www.cyberciti.biz/fb/>
  5. # This script is licensed under GNU GPL version 2.0 or above
  6. # -------------------------------------------------------------------------
  7. # This script is part of nixCraft shell script collection (NSSC)
  8. # Visit http://bash.cyberciti.biz/ for more information.
  9. # ----------------------------------------------------------------------
  10. IPT=/sbin/iptables
  11. SPAMLIST="spamlist"
  12. SPAMDROPMSG="SPAM LIST DROP"
  13. BADIPS=$(egrep -v -E "^#|^$" /root/iptables/blocked.ips)
  14.  
  15. # create a new iptables list
  16. $IPT -N $SPAMLIST
  17.  
  18. for ipblock in $BADIPS
  19. do
  20. $IPT -A $SPAMLIST -s $ipblock -j LOG --log-prefix "$SPAMDROPMSG"
  21. $IPT -A $SPAMLIST -s $ipblock -j DROP
  22. done
  23.  
  24. $IPT -I INPUT -j $SPAMLIST
  25. $IPT -I OUTPUT -j $SPAMLIST
  26. $IPT -I FORWARD -j $SPAMLIST


4000+ howtos and counting! If you enjoyed this article, join 45000+ others and get free email updates!

Click here to subscribe via email.

  • Igor

    How can I remove ip’s from blocked

  • Charon

    I think rule
    $IPT -I OUTPUT -j $SPAMLIST
    is incorrect. Because in this case $ipblock is destination (-d), not source (-s)

  • parbat

    hi

    everybody now will come big platform

  • Andre

    i wanna allow just this ip [10.0.0.100 - 10.0.0.112, 10.0.0.2, 10.0.0.3] and block other ip how is the configuration.
    please send to my email : nseshop@gmail.com

    thanks very much

  • peace

    hi i new to iptables where exactly should i write this script any help
    please
    thanks for any help appreciated.

  • dodger

    thanks for this script..
    btw i have some error with “BADIPS=$(egrep -v -E “^#|^$” /root/iptables/blocked.ips)”
    with -E swich… i change it to -e and its work fine
    in egrep –help no -E option

    ubuntu 10.04

  • gamecp

    great script!

  • Ghulam Sakhi

    Dear Reader.
    you can remove IP from block by this short command
    #iptables -D input -s 172.20.7.12 IP ADDRESS -j DROP
    172.20.7.12 is an example you can remove any IP that you want just type instate

  • Erik

    i have a ip that i want to block 78.47.53.243 in my dreambox ???

    please..

Previous Script:

Next Script: