Run a Bash script to set up iptables at startup [duplicate]

I'm using Ubuntu 16.04 Server.

I want to use a Bash script for iptables at startup, but I dont wanna use crontab or init.d. Is there any possible way to achieve this without them?

#!/bin/bash
IPT="/sbin/iptables"
$IPT --flush
$IPT --delete-chain
$IPT -P INPUT DROP
$IPT -P FORWARD DROP
$IPT -P OUTPUT ACCEPT
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT
$IPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT*
1

3 Answers

If you do not want to install additional software, one possible workaround that works on Ubuntu 16.04 is to create two scripts one which will save the Iptables current configuration and one which will restore it. These scripts must be placed in (or sim-linked to) /etc/network/if-post-down.d/ and /etc/network/if-pre-up.d/. Also must be executable files and must not have any extensions, like .sh. Here is how these scripts look on my system:

$ cat /etc/network/if-post-down.d/iptables-save
#!/bin/sh
/sbin/iptables-save > /root/iptables-current-state.dat
exit 0
$ cat /etc/network/if-pre-up.d/iptables-restore
#!/bin/sh
/sbin/iptables-restore < /root/iptables-current-state.dat
exit 0
1

On my 16.04 servers I use the /etc/network/interfaces file method:

$ cat /etc/network/interfaces
# interfaces file for smythies.com 2016.01.30
# attempt to set local DNS herein, as the method
# used with the old 12.04 server no longer works.
#
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
pre-up /home/doug/init/doug_firewall
dns-nameservers 127.0.0.1
# The primary interface (d-link PCI card)
auto enp4s0
iface enp4s0 inet dhcp
# Local network interface (uses built in ethernet port)
auto enp2s0
iface enp2s0 inet static address 192.168.111.1 network 192.168.111.0 netmask 255.255.255.0 broadcast 192.168.111.255

Where you see I use a pre-up directive in the local interface definition to execute my (mainly) iptables script.

NOTE: this method will not work with later releases that use netplan instead of ifup ifdown.

2

You can add the startup script to Ubuntu startup applications. There are detailed instructions here (). Remember you make your script executable before you add it to the startup applications.

6

You Might Also Like