Updating UFW firewall to use Dynamic IP

I use Ubuntu for server instances however they are all secured using UFW.  The one issue I run into occasionally is when my ISP changes my IP.  It does not happen often, but it does happen and then it becomes a major pain to go through the process of updating all of them.  I did some searching and am putting this together in hopes it will help others.

First let me say, use at your own risk.  I am using this successfully but that does not mean it will work perfect for you.

I created a new directory called “p_scripts” and it holds personal scripts
sudo mkdir /p_scripts

I created a script in that folder called “dynamicip.sh”
nano /p_scripts/dynamicip.sh

Paste this into the new file:
#!/bin/bash

HOSTNAME=YOUR_DYNAMIC_HOST_NAME
LOGFILE=/p_scripts/dynamicip.log

Current_IP=$(host $HOSTNAME | cut -f4 -d’ ‘)

if [ $LOGFILE = “” ] ; then
iptables -I INPUT -i eth1 -s $Current_IP -j ACCEPT
echo $Current_IP > $LOGFILE
else

Old_IP=$(cat $LOGFILE)

if [ “$Current_IP” = “$Old_IP” ] ; then
echo IP address has not changed
else
iptables -D INPUT -i eth1 -s $Old_IP -j ACCEPT
iptables -I INPUT -i eth1 -s $Current_IP -j ACCEPT
/etc/init.d/iptables save
echo $Current_IP > $LOGFILE
echo iptables have been updated
fi
fi
# cronjob
# */5 * * * * sh /p_scripts/dynamicip.sh > /dev/null 2>&1

I then did a simple:
chmod 755 /p_scripts/dynamicip.sh

Create empty log file:
touch /p_scripts/dynamicip.log

To test it, just run:
sh /p_scripts/dynamicip.sh

If you view the log file, it will have your actual IP address.

To automate this process, simply add a cronjob to run however often you want, I use 5 minutes:
*/5 * * * * sh /p_scripts/dynamicip.sh > /dev/null 2>&1

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.