Script For Saving Iptables And Restoring Them After Server Restart In Ubuntu


If you are like me who’s website is hosted on Ubuntu server, there will arise a need when you will need to block certain IP addresses. These IP addresses are mostly spam and malicious that never benefits you in any way. In my post a few weeks back I discussed how to add IP addresses to Iptables quickly. But in a worse case scenario when you need to restart your server, all data in iptables will be lost. So how would you make sure that the data is not lost and can be restored?

For those who don’t know, Iptables is the default firewall in Ubuntu through which you can block certain IP addresses. Before configuring so that the IP addresses can be restored after server restart, first lets make sure that the iptables configuration is saved.

You can save the configuration by typing this command in your Terminal using PuTTY or any other tool:

iptables-save > /root/working.iptables.rules

This command will save your iptables configuration in root folder and name it working.iptables.rules.

Now to restore these iptables anytime, run the following command:

iptables-restore < /root/working.iptables.rules

But this method only restores the iptables when entered manually. What we want is to actually restore the iptables automatically when the server restarts. For this, you need to navigate to /etc/network folder and then edit Interfaces using WinSCP or any other tool.

editing interfaces

Copy/Paste the following code under auto eth0,

pre-up iptables-restore < /root/working.iptables.rules

as shown in the following screenshot.

restoring iptables

Now go ahead and restart the server to see if your iptables have been automatically restored. Enter iptables –L in Terminal to confirm. That’s all. Enjoy!

  • FishGuy876

    Thanks for the tip. My new dedicated box running Ubuntu/DirectAdmin was getting hammered with requests shortly after going online, now I have an easy way to block offending IP’s. Thanks!