How do I use bash to bulk add a file full of IP blocks to IPTables

How can I bulk add a text file full of IP blocks to IPTables using BASH (or another scripting language)? Or is there some other way of blocking these address ranges?

EDIT: In other words is there a way to program something to iterate through the file and build the relevant entries?

Upvotes: 8

Views: 5451

Answers (3)

JuZer
JuZer

Reputation: 783

You can parse ip list and check whether IP address is already blocked or no:

#!/bin/bash

for i in $(cat iptables.log)
do
    /sbin/iptables -L -n -v | grep -q "${i}"
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
     /sbin/iptables -A INPUT -s "${i}" -j DROP
    fi
done

Upvotes: 5

Leo
Leo

Reputation: 64

Excessive number of requests and bandwidth use might be caused by bots from search engines trying to crawl your site and also when sites like facebook or linkedin create thumbnails because someone is linking to your site from social media.

For stopping bots you should use the robots.txt file on your site. Read more about the file and configuring it at robotstxt.org. I think there is also several posts about it on stackoverflow.

Upvotes: 0

Joshua Terrill
Joshua Terrill

Reputation: 2017

Could you just create a loop within your iptables config script? Something like

#!/bin/bash
for x in $(cat ip_list.txt)
do
    iptables -A INPUT -s $x -j DROP
done

Where your ip_list.txt file would just look like

1.1.1.1
2.2.2.2
3.3.3.3
etc

Upvotes: 15

Related Questions