Category Archives: Ubuntu

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 “”
nano /p_scripts/

Paste this into the new file:


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

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

Old_IP=$(cat $LOGFILE)

if [ “$Current_IP” = “$Old_IP” ] ; then
echo IP address has not changed
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
# cronjob
# */5 * * * * sh /p_scripts/ > /dev/null 2>&1

I then did a simple:
chmod 755 /p_scripts/

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

To test it, just run:
sh /p_scripts/

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/ > /dev/null 2>&1