Charlie Harvey

Tip: Blocking spam with iptables on GNU/Linux

Fried spam

Spam is a constant problem for me as a sys admin. Even after greylisting and denyhosts and fail2banning I still find myself wanting to deny access to the occasional ip address. The project iptables provides a pretty nice firewall for the Linux kernel. I often forget the syntax and I often try to ban an IP that I’ve already banned elsewhere. This is a script that I use to ban IPs on the GNU/Linux machines that I admin.

Banning an IP address with iptables is as simple as typing $ sudo iptables -v -A INPUT -s -j DROPThat command would drop any packets received from – replace with the IP you want to block and you're away. But you can end up creating duplicate rules when doing this. No big deal but a script tidies things up a little. It also saves me having to remember to sudo, which for a lazy person like me us a plus!

$ cat `which` #!/bin/bash if [ $# = 1 ]; then LOOKUP=`sudo iptables -nL | grep $1` if [ -z "$LOOKUP" ]; then echo Blocking $1 sudo iptables -v -A INPUT -s $1 -j DROP else echo ALREADY BLOCKED echo $LOOKUP fi else echo Must get exactly 1 IP address to spam block fi We first check that exactly one IP was received (the IP to block). If not we give a warning and exit. If we did get an IP we check it isn't blocked and if not block it. Simple as that.

And you use it thus (note that I am already root in this session).# Blocking DROP all opt -- in * out * -> # ALREADY BLOCKED DROP all --

Even a Bash script as seemingly trivial as this can save typing, forgetting to sudo and duplicate iptables rules. Enjoy.


  • Be respectful. You may want to read the comment guidelines before posting.
  • You can use Markdown syntax to format your comments. You can only use level 5 and 6 headings.
  • You can add class="your language" to code blocks to help highlight.js highlight them correctly.

Privacy note: This form will forward your IP address, user agent and referrer to the Akismet, StopForumSpam and Botscout spam filtering services. I don’t log these details. Those services will. I do log everything you type into the form. Full privacy statement.