DEV Community


Posted on

dynamic dns and ufw

Github Gist Link: Gist

Own a vps? I scored over black friday and now have a ton of them for some projects. I ended up setting up wireguard on all of them and linking them all together. I have a raspberry pi in my home for my private container registry and hooked it up to the wireguard network.

I did not want to open up my wireguard port and any ssh port to the public.

I found a similar script like this on a google search, had to modify it for ufw to work and to do wireguard and ssh. My home router does a dynamic dns update and keeps that updated. If your router cannot do that, you can setup a pi or a script to run off your computer so when it boots up it will try to keep it up to date.

UFW cannot accept a dns name, unfortunately. This script will require the host command, if your vps does not have that command, it is usually in bind-utils on ubuntu or dns-utils. Add in your hostname and ssh port, wireguard port. Run it manually first to verify it works and then cron it.

sudo chmod +x
sudo ./
sudo ufw status
Enter fullscreen mode Exit fullscreen mode

You should see your home network ip allowed for ssh and wireguard.

Here is the script:



#IF IT DOES NOT WORK, AT LEAST ON UBUNTU INSTALL, bind-utils to get the host command

#Create a cron /15 * * * * root bash /path/to/

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
new_ip=$(host $HOSTNAME | head -n1 | cut -f4 -d ' ')
old_ip=$(/usr/sbin/ufw status | grep $HOSTNAME | head -n1 | tr -s ' ' | cut -f3 -d ' ')
if [ "$new_ip" = "$old_ip" ] ; then
    echo IP address has not changed
    if [ -n "$old_ip" ] ; then
        /usr/sbin/ufw delete allow from $old_ip to any port $SSH_PORT
        /user/sbin/ufw delete allow from $old_ip to any port $WIREGUARD_PORT
    /usr/sbin/ufw allow from $new_ip to any port $SSH_PORT comment $HOSTNAME
    /usr/sbin/ufw allow from $new_ip to any port $WIREGUARD_PORT comment $HOSTNAME
    echo UFW have been updated
Enter fullscreen mode Exit fullscreen mode

I use this so now my home network can reach my vps network via wireguard or ip and I can vpn into my home network to jump. Very cool!

Latest comments (1)

adj79 profile image

Great script, thanks!
I just changed new_ip=$(host $HOSTNAME | head -n1 | cut -f4 -d ' ') to new_ip=$(getent hosts $HOSTNAME | awk '{ print $1 }').
Should work on most systems and more importantly (at least in my case): it handles CNAME entries as $HOSTNAME as well as A records easier, since the host IP should always be first in line.