Skip to main content
This script is useful for both VPS and Bare Metal customers who want to restrict SSH access to their own IP without manually updating firewall rules every time their ISP assigns a new address.

Prerequisites

  • A Dynamic DNS hostname (e.g., from DuckDNS, No-IP, Dynu, or your router’s built-in DDNS)
  • dig installed (dnsutils on Debian/Ubuntu, bind-utils on RHEL)

UFW Script

For servers using UFW (Debian / Ubuntu):

firewalld Script

For servers using firewalld (RHEL / AlmaLinux / Rocky):

Installation

Save the appropriate script for your firewall:
Edit the configuration variables at the top:

Setting Up the Cron Job

Run the script every 5 minutes to keep the firewall in sync:

How It Works

  1. The script resolves your DDNS hostname to its current IP address
  2. It compares the result against the last known IP (stored in /var/tmp/ddns-firewall-last-ip)
  3. If the IP has changed, it removes the old firewall rule and adds a new one for the current IP
  4. If DNS resolution fails, the script exits without modifying any rules (your existing access is preserved)
  5. All changes are logged to /var/log/ddns-firewall.log

Verifying

After the cron runs, confirm the rule is in place:
Check the log for recent activity:
This script manages a single rule for one DDNS hostname. If you have multiple dynamic IPs (home, office, etc.), create separate copies of the script with different DDNS_HOSTNAME and STATE_FILE values.