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)
diginstalled (dnsutilson Debian/Ubuntu,bind-utilson RHEL)
- Debian / Ubuntu
- RHEL / AlmaLinux / Rocky
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:Setting Up the Cron Job
Run the script every 5 minutes to keep the firewall in sync:How It Works
- The script resolves your DDNS hostname to its current IP address
- It compares the result against the last known IP (stored in
/var/tmp/ddns-firewall-last-ip) - If the IP has changed, it removes the old firewall rule and adds a new one for the current IP
- If DNS resolution fails, the script exits without modifying any rules (your existing access is preserved)
- All changes are logged to
/var/log/ddns-firewall.log
Verifying
After the cron runs, confirm the rule is in place:- UFW
- firewalld