IPTables quick setup script

Sometimes it is necessary, for example, to delete all IPTables rules and to add only the necessary, so for convenience, you can specify them in the script, and then execute it.

Switch to root user, in Ubuntu it can be done like this:

sudo -i

First, look at the existing rules (maybe some will be needed and they can be copied to the script):

iptables -nvL
iptables -L -t nat
iptables -L -t mangle

And actually below I will give an example of a script with imbued IPTables rules:

#!/bin/sh
# An example of cleaning and deleting all existing rules and chains
iptables -t filter -F
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -t filter -X
iptables -t nat -X
iptables -t mangle -X
iptables -X
# We will block all incoming and forward connections, allow all outgoing from the server
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow local interface
iptables -A INPUT -i lo -j ACCEPT
# Do not touch already established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Open the ports SSH, HTTP, HTTPS for all if needed
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# If necessary, you can allow all incoming connections to a specific IP address.
iptables -A INPUT -s 192.168.10.101 -j ACCEPT
# Allow PING
iptables -A INPUT -p icmp -j ACCEPT
iptables -A OUTPUT -p icmp -j ACCEPT
# etc.

Make the script file executable:

chmod +x rules.sh

Run it:

./rules.sh

See also my articles:
How to save IPTables rules
How to configure IPTables

Leave a comment

Leave a Reply