Archive

Posts Tagged ‘load’

Load iptables on startup, save on shutdown

November 23rd, 2012 No comments

Wrote some scripts that store iptables automatically after interface goes down and reloads after startup.

sudo su -
mkdir /etc/network/firewall-backup
touch /etc/network/if-pre-up.d/firewall-up && chmod +x /etc/network/if-pre-up.d/firewall-up
touch /etc/network/if-post-down.d/firewall-down && chmod +x /etc/network/if-post-down.d/firewall-down

Add the following to the firewall-up script:

#!/bin/sh -e
/sbin/iptables-restore < /etc/network/firewall-ip4.conf
/sbin/ip6tables-restore < /etc/network/firewall-ip6.conf

Create the initial config:

/sbin/iptables-save > /etc/network/firewall-ip4.conf
/sbin/ip6tables-save > /etc/network/firewall-ip6.conf

Add the following to the firewall-down script:

#!/bin/sh -e
now=`date +%F_%H:%M:%S`
 
# Backup ipv4 config if necessary
md5sum_old=$(cat /etc/network/firewall-ip4.conf | sed -e '1,7d;$d;' | md5sum)
md5sum_new=$(/sbin/iptables-save | sed -e '1,7d;$d;' | md5sum)
 
if [ "$md5sum_old" != "$md5sum_new" ]; then
        cp /etc/network/firewall-ip4.conf /etc/network/firewall-backup/firewall-ip4_$now.conf
fi
 
# Always save because we want to retain stats
/sbin/iptables-save > /etc/network/firewall-ip4.conf
 
# Backup ipv6 config if necessary
md5sum_old=$(cat /etc/network/firewall-ip6.conf | sed -e '1,7d;$d;' | md5sum)
md5sum_new=$(/sbin/ip6tables-save | sed -e '1,7d;$d;' | md5sum)
 
if [ "$md5sum_old" != "$md5sum_new" ]; then
        cp /etc/network/firewall-ip6.conf /etc/network/firewall-backup/firewall-ip6_$now.conf
fi
 
# Always save because we want to retain stats
/sbin/ip6tables-save > /etc/network/firewall-ip6.conf

Your iptables will now be stored when the interface is brought down and a backup of your config is made if any rules have changed in the meanwhile.

Categories: Linux Tags: , , , ,