← cd ~/blog

less iptables-remove-duplicate-rules.md

iptables: remove duplicate rules

#Crumbs

It can happen that the rules you manage with iptables suddenly grow into the hundreds. Some of them, however, might be simple duplicates.

The tool that effectively comes to the rescue is certainly awk. Put into a script, it becomes great.

/sbin/iptables-save | awk '!COMMIT||!x[$0]++'

Let’s put it into a script that does the job the way it should be done:

#!/bin/sh

/sbin/iptables-save | awk '!COMMIT||!x[$0]++' > /tmp/tmp_iptables.conf
uniq /tmp/tmp_iptables.conf > /tmp/iptables.conf

echo "Stopping firewall and allowing everyone..."
iptables -F
iptables -X
iptables -t raw -F
iptables -t raw -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

echo "Reactivating firewall ..."
/sbin/iptables-restore < /tmp/iptables.conf

echo "All done!"

if [ -f /tmp/iptables.conf ] ; then /bin/rm -f /tmp/iptables.conf ; fi
if [ -f /tmp/tmp_iptables.conf ] ; then /bin/rm -f /tmp/tmp_iptables.conf ; fi

exit 0

Easy, right?