Iptables – How to load a list of addresses into iptables, dynamically

iptables

Now, I want to dynamic loading a ip list file for iptables .the ip list file is the accept host , default drop .
example,

iptables -A INPUT -p tcp --dport 1111 -s 2.2.2.2 -j ACCEPT
iptables -A INPUT -p tcp --dport 1111 -j DROP
iptables -A INPUT -j ACCEPT

I mean to open a port for some one , but the ip list is dynamic,Whether I can do like below ,

iptables -A INPUT -p tcp --dport 1111 -s ip-list-file -j ACCEPT
iptables -A INPUT -p tcp --dport 1111 -j DROP
iptables -A INPUT -j ACCEPT

ip-list-file:
2.2.2.2
3.3.3.3 

Have any idea ? Thank you .

=========================================

I look at Iptables rules sometimes are reset automatically , I can use -I ,insert the rule to head of the chain .
How to realize the dynamic loading the ip list file ?

Best Answer

You can't simply provide a filename to the -s parameter. If you only have a few addresses (in the order of 10s), you can use a script to add multiple rules:

while read IP; do
    iptables -A INPUT -p tcp --dport 1111 -s $IP -j ACCEPT
done < ip-list-file

If you have lots of addresses you should rather use the ipset mechanism:

ipset create list0 iphash
while read IP; do
    ipset add list0 $IP
done < ip-list-file
iptables -A INPUT -p tcp --dport 1111 -m set --match-set list0 src
Related Topic