Start iptables in Debian Automatically

5
by on February 21, 2013 at 9:47 pm

If you are trying to make iptables survive a reboot in Debian Squeeze or Wheezy, you may find the following of use.  After you get your iptables all squared away, save them to a text file with the incredibly handy /sbin/iptables-save command:

/sbin/iptables-save > /root/iptables.saved

This will create a text file in the /root directory containing lines that will be parsed by iptables when used with the  iptables-restore command.

Next, add the following script to your system:

#!/bin/sh
### BEGIN INIT INFO
# Provides: iptables
# Required-Start: mountkernfs $local_fs
# Required-Stop: $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Set up iptables rules
### END INIT INFO
/sbin/iptables-restore < /root/iptables.saved
case "$1" in
 *)
 echo "iptables loaded from file"
 ;;
esac
exit 0

Save that script to /etc/init.d/iptables

Next, run update-rc.d iptables defaults

You should now see SXXiptables in /etc/rc2.d/ and other run level directories, where XX is a number.

in Debian, How-To

, , , ,

You can skip to the end and leave a response. Pinging is currently not allowed.

  • marcos

    Hi,
    I have a question:
    If I just create a script /etc/init.d/iptables without run the command
    update-rc.d iptables defaults

    The script /etc/init.d/iptables will be executed when the machine reboot ?

    Thanks.

    • http://www.zipref.com Mike

      No, if you do not run update-rc.d then the script won’t be run on boot. update-rc.d creates the symlinks in each /etc/rc.X/ directory which instructs the system which scripts in /etc/init.d/ it should run for each run level.

      • marcos

        Thanks Mike.

  • Chris

    Hello,

    I have followed the instructions exactly. Unfortunately, I get the following error here:

    /etc/init.d/iptables: line 10: lt: command not found
    /root/iptables.saved: line 2: *nat: command not found
    ….
    /root/iptables.saved: line 54: COMMIT: command not found
    iptables loaded from file

    Have you any idea about this?

    • http://www.zipref.com Mike

      Chris, thank you for the comment. I noticed that my blog converted a ‘less than’ bracket ( < ) to < which is the html equivalent of that character. I have fixed the script on this page. Basically, it looked like you were trying to run the iptables.saved file as a script, which it is not. It’s simply a list of iptables rules that are read in by the iptables-restore command.

Categories