Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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.

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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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