Skip to content

Instantly share code, notes, and snippets.

@nickolasdeluca
Last active February 27, 2026 12:29
Show Gist options
  • Select an option

  • Save nickolasdeluca/f46dacb365313dc7137946699700f3dd to your computer and use it in GitHub Desktop.

Select an option

Save nickolasdeluca/f46dacb365313dc7137946699700f3dd to your computer and use it in GitHub Desktop.
replace-iptables-for-ufw
#!/usr/bin/env bash
set -euo pipefail
# Must run as root (or via sudo)
if [[ "${EUID}" -ne 0 ]]; then
echo "Please run as root (e.g., sudo $0)"
exit 1
fi
echo "==> Flushing iptables (filter/nat/mangle/raw) and resetting policies to ACCEPT..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -t raw -F
iptables -t raw -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
echo "==> Flushing nftables ruleset..."
nft flush ruleset || true
echo "==> Updating apt and installing ufw..."
export DEBIAN_FRONTEND=noninteractive
apt update
apt install -y ufw
echo "==> Configuring UFW defaults..."
ufw default deny incoming
ufw default allow outgoing
echo "==> ALWAYS allowing SSH (22/tcp)..."
ufw allow 22/tcp
# --- Port prompt (EXCLUDING 22) ---
echo
echo "Optional additional TCP ports to allow (do NOT include 22)."
echo "Enter a space/comma-separated list (e.g., '80 443' or '80,443')."
read -r -p "Additional ports [default: none]: " ports_input
# Normalize separators to spaces, split into array (if any)
ports_input="${ports_input//,/ }"
ports_input="$(echo "$ports_input" | xargs || true)" # trim (xargs is in coreutils)
if [[ -n "${ports_input}" ]]; then
read -r -a ports <<< "$ports_input"
echo "==> Allowing additional ports:"
for p in "${ports[@]}"; do
# Allow formats: "80" or "80/tcp"
if [[ "$p" =~ ^[0-9]{1,5}(/tcp)?$ ]]; then
port_num="${p%/tcp}"
if (( port_num < 1 || port_num > 65535 )); then
echo "Invalid port range: $p"
exit 1
fi
if (( port_num == 22 )); then
echo "Port 22 is always allowed; do not include it in the list."
exit 1
fi
echo " - ${port_num}/tcp"
ufw allow "${port_num}/tcp"
else
echo "Invalid port entry: '$p' (use numbers like 80 or 443)"
exit 1
fi
done
else
echo "==> No additional ports requested."
fi
echo "==> Enabling UFW..."
ufw --force enable
echo "==> UFW status:"
ufw status verbose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment