Skip to content

Instantly share code, notes, and snippets.

@vkartk
Created December 5, 2022 05:12
Show Gist options
  • Save vkartk/0bfbd75eacf94e3f2a87ee05136ae13a to your computer and use it in GitHub Desktop.
Save vkartk/0bfbd75eacf94e3f2a87ee05136ae13a to your computer and use it in GitHub Desktop.
UFW ssh access from dynamic ip
#!/bin/bash
HOSTNAME=dynamicdns.tld # Your Dynamic DNS Hostname
PORT=22 # SSH Port
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
new_ip=$(host $HOSTNAME | head -n1 | cut -f4 -d ' ')
old_ip=$(/usr/sbin/ufw status | grep $HOSTNAME | head -n1 | tr -s ' ' | cut -f3 -d ' ')
now=$(date)
if [ "$new_ip" = "$old_ip" ] ; then
echo [ $now ]:[ $old_ip ] IP address has not changed.
else
if [ -n "$old_ip" ] ; then
/usr/sbin/ufw delete allow from $old_ip to any port $PORT
fi
/usr/sbin/ufw allow from $new_ip to any port $PORT comment $HOSTNAME
echo [ $now ]: UFW iptables have been updated. [ $old_ip ] => [ $new_ip ]
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment