My new service provider does not assign static IP addresses to its customers so I had find a way around this issue in order to connect to the servers quickly from home.
Because my IP address is constantly changing, and not even within a consistent set of address blocks, I decided to use my personal domain name as the access point.
See here for information on setting up Dynamic DNS.
iptables will detect and resolve the ip address for any hostnames in the configuration file only the first time the service is started, so this is not ideal for a hostname with a changing (dynamic) IP address. This is why we need to use a script that will detect any changes and force iptables to restart.
I found this script below from here and it does everything I need it to do perfectly (change the values highlighted below to suit your own needs):
#!/usr/bin/python
# Version 1.0
# 6 January 2014
# Jason Bickley - Senior Web Manager
# Dynamic DNS script to update IP address for home network
import os
def gettextoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
pipe = os.popen(cmd + ' 2>&1', 'r')
text = pipe.read()
if text[-1:] == '\n': text = text[:-1]
return text
home_dyndns = "home.jasonbickley.net"
log_dyndns = "/var/log/dyndns.log"
all_dyndns = "/var/log/dyndns-all.log"
last_dyndns = gettextoutput("cat " + log_dyndns)
curr_dyndns = gettextoutput("host " + home_dyndns)
print "Log: "+ last_dyndns
print "Cur: "+ curr_dyndns
if last_dyndns == curr_dyndns:
print "IPs match, no restart necessary"
else:
print "Updating last IP with current"
os.system("echo '" + curr_dyndns + "' > " + log_dyndns)
os.system("echo `date '+%Y%m%d %H:%M:%S'` '" + curr_dyndns + "' >> " + all_dyndns)
print "Restarting iptables to update it"
os.system("/etc/init.d/iptables restart")
Here is a summary of what the script above does:
It checks the IP address in the file /var/log/dyndns.log and compares the IP address with my subdomain’s (home.jasonbickley.net).
If the IP addresses match, then it does nothing. If they differ, it overwrites the IP address file with the new value, logs more specific details in /var/log/dyndns-all.log, and restarts the iptables service. This means that iptables now has the updated value for my subdomain.
I put the script here /root/Scripts/dyndns.py, chmod 700 it, and created a cron entry to run it every 10 mins.