This script will configure the ufw of target host to allow HOSTNAME access.
user@host ~ # mkdir -p scripts/dynip user@host ~ # cd scripts/dynip
#!/usr/bin/bash HOSTNAME=<HOSTNAME> # <-- set this to your dynamic hostname BASEDIR=$HOME/scripts/ufw # <-- set this to the created directory IPFILE=${BASEDIR}/currip LOGFILE=${BASEDIR}/ufw.log Current_IP=$(host ${HOSTNAME} | head -n1 | cut -f4 -d ' ') NOW=$(date) echo "${NOW} - Current IP: ${Current_IP}" >> ${LOGFILE} if [ ! -f ${IPFILE} ]; then /usr/sbin/ufw allow from ${Current_IP} to any port 22 proto tcp echo ${Current_IP} >> ${IPFILE} else Old_IP=$(cat ${IPFILE}) echo "${NOW} - Old IP: ${Old_IP}" if [ "${Current_IP}" = "${Old_IP}" ] ; then echo ${NOW} - IP address has not changed >> ${LOGFILE} else /usr/sbin/ufw delete allow from ${Old_IP} proto tcp to any port 22 /usr/sbin/ufw allow from ${Current_IP} proto tcp to any port 22 /usr/sbin/ufw delete allow from ${Old_IP} proto tcp to any port 81 /usr/sbin/ufw allow from ${Current_IP} proto tcp to any port 81 #/usr/sbin/ufw delete allow from ${Old_IP} proto tcp to any port 9000 #/usr/sbin/ufw allow from ${Current_IP} proto tcp to any port 9000 #/usr/sbin/ufw delete allow from $Old_IP proto tcp to any port 80 #/usr/sbin/ufw allow from $Current_IP proto tcp to any port 80 echo ${Current_IP} > ${IPFILE} /usr/sbin/ufw status numbered >> ${LOGFILE} echo ${NOW} - iptables have been updated >> ${LOGFILE} fi fi