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?

1 Answer 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.

  • Sorry, was thinking "IP blacklist". It should be ACCEPT, and I've modified my answer to suit.
    – womble
    Aug 13, 2011 at 4:28
  • Actually, there's a UUOC in here.. You don't need to cat into while, just do: ... done < allow.file .. instead Aug 13, 2011 at 11:48
  • 1
    @Tom Well caught.
    – womble
    Aug 13, 2011 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.