Saturday, April 6, 2013

Quickly add rules to IPTABLES on CentOS/RHEL 5.x using a script

Older iptables lack the -C switch so you have to use bash to check whether a rule already exists before appending it. Works like this:

if [ ! "`iptables-save | grep 'dport 21'`" ]; then iptables -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT;fi
if [ ! "`iptables-save | grep 'dport 22'`" ]; then iptables -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT;fi
if [ ! "`iptables-save | grep 'dport 80'`" ]; then iptables -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT;fi
service iptables save
Probably not the most elegant solution, but it works. 

No comments:

Post a Comment