Sometimes the fastest way out of a broken firewall is to wipe it. This script returns iptables to a completely clean state: all policies set to ACCEPT, every rule flushed and every custom chain removed.
The server is left with no firewall at all after running it. On a machine reachable from the internet, use it only as a step towards loading a known-good ruleset.
The Reset Script
Save it, make it executable and run it as root:
Why the Order Matters
The policies are set to ACCEPT before anything is flushed, and that is the whole reason the script is safe to run over SSH.
If the INPUT policy is DROP and the rules are flushed first, the rule that allowed port 22 disappears while the default is still DROP. The session dies on the next packet and the server is unreachable until someone reaches the console.
-F flushes the rules, -X deletes the empty user-defined chains that are left behind. Both are run per table, because flushing filter does not touch nat, mangle or raw.
Reset IPv6 As Well
A clean IPv4 firewall means nothing if IPv6 is still filtered. Repeat the same commands with ip6tables:
Verify the Result
List every table and confirm that all chains are empty and every policy reads ACCEPT:
The short form shows the whole ruleset at once, which is easier to scan:
Back Up Before, Persist After
Take a snapshot before wiping anything, so the old ruleset can be restored:
Restoring it is a single command:
The reset itself lives only in memory. On a system with iptables-persistent the saved rules come back on the next boot, so the empty state has to be saved as well if it is meant to survive a restart:
If Docker, UFW, firewalld or fail2ban are running on the machine, they will rebuild their own chains anyway, either on their next restart or within seconds. Restart or stop those services deliberately instead of expecting the flush to keep them away.