Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

Block and Allow IP with iptables – simple script

As most developers are lazy, I’m a huge fan of scripts. I’ve found myself lately having to add entries to iptables to block a single IP or a small subnet, so I made a quick script to make the job easier on myself.

Usage for both of these is of course really simple. Say 123.1.2.3 is the IP in question:

sudo ./blockip.sh 123.1.2.3
sudo ./allowip.sh 123.1.2.3

blockip.sh Blocks the IP using iptables

1
2
3
4
5
6
7
#!/bin/bash

#blocking iptables
/sbin/iptables -A INPUT -s $1 -j DROP

#saving iptables
/sbin/iptables-save > /etc/sysconfig/iptables

allowip.sh Removes the entry from iptables

1
2
3
4
5
6
7
#!/bin/bash

#allowing iptables
/sbin/iptables -D INPUT -s $1 -j DROP

#saving iptables
/sbin/iptables-save > /etc/sysconfig/iptables

This entry was posted in linux, scripting and tagged , . Bookmark the permalink.

2 Responses to Block and Allow IP with iptables – simple script

  1. defunkt says:

    now… to be even more lazy…

    how bout a cron script that checks the amount of connections per host, and if above thresh-hold X will call your blockip.sh.

    dynamic firewall for certain types of attacks.. im actually looking at writing one, just havnt been successfull as of yet.

    netstat -atun | awk ‘{print $5}’ | cut -d: -f1 | sed -e ‘/^$/d’ |sort | uniq -c | sort -n -r

    any hints?

  2. Free says:

    The command you have _appends_ a rule.
    If your default policy is to DROP it will not work.
    The allow command must change to _insert_ a rule.
    Instead of -A use -I
    Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>