Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 601
Matthew Brown aka Lord Matt Avatar asked Jun 08 '14 03:06

Matthew Brown aka Lord Matt


2 Answers

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
like image 119
Joshua Terrill Avatar answered Nov 01 '22 13:11

Joshua Terrill


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
like image 29
JuZer Avatar answered Nov 01 '22 13:11

JuZer