Allow a range of IP's with IPTABLES from a file

I would like to allow only certain ip ranges (CIDR) and block everything else, however, I have those IPs that I want to allow on a text file. How could I load them up from the allow.file to IPTABLES interface eth0?


Solution 1:

Off the top of my head:

while read range; do
    iptables -A INPUT -i eth0 -s $range -j ACCEPT
done < allow.file

Addendum: A comment in chat asked whether using -I INPUT might be better than -A INPUT -- that is, inserting the rule at the beginning of the chain rather than at the end of the chain. This is, really, a local issue -- I've seen firewall rulesets where inserting would break things, and rulesets where appending would break things. You've got to make that choice for yourself and your situation. If you don't know which, then you shouldn't be writing iptables rules by hand, and should be using a management program like shorewall or ufw.