Skip to content

Instantly share code, notes, and snippets.

@k14i
Created June 27, 2013 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k14i/5874559 to your computer and use it in GitHub Desktop.
Save k14i/5874559 to your computer and use it in GitHub Desktop.
This script makes iptables ACCEPT specific CIDRs in a list file. Python >= 2.4 is required (so this can work on legacy OS like CentOS 5.x). It is good to call this script in the start() function of /etc/init.d/iptables.
#!/usr/bin/env python
import re
import os
file = "/root/etc/iptables/accept/cidr"
regex = re.compile('^([0-9]{1,3})(\.([0-9]{1,3})){3}/[0-9]{1,2}')
os.system("iptables -F")
os.system("iptables -A INPUT -i lo -p all -j ACCEPT")
f = open(file, "r")
for line in f.readlines():
matchobject = regex.match(line)
if matchobject == None:
continue
else:
cidr = matchobject.group()
cmd = "iptables -A INPUT -s %(cidr)s -j ACCEPT" % locals()
os.system(cmd)
f.close()
os.system("iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT")
os.system("iptables -A INPUT -j DROP")
os.system("iptables -A OUTPUT -j ACCEPT")
os.system("iptables -P INPUT DROP")
os.system("iptables -P FORWARD DROP")
os.system("iptables -P OUTPUT DROP")
os.system("iptables -nL")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment