3

Quick Python Workaround For Dynamic DNS

mailboxx
As many of you know I have recently moved my website onto a personal Raspberry Pi server conveniently located in my bedroom. Well, to make a long story short I have a dynamic IP address which means that it switches once in a while and if I’m not at home to check the new address with ipconfig and change it through my Domain Name dash then my site is down until I can do so. If you have ever had this happen to you then you know it’s annoying as hell.

You used to be able to enlist in the services of DynDNS, No-IP, and ZoneEdit for free, but those days are gone and I refuse to pay $30 a month for them to switch my IP perhaps 2 to 4 times a year so I decided to come up with a little solution of my own. I wrote a script in Python that is meant to be run automatically at the startup of the server. Every 15 minutes it will check if my IP is still the same and if it detects a change it emails me directly to my phone where I can simply go to my Domain Name dash and change my @ address. This means that I will have approximately 15 – 30 minutes of downtime whenever my IP changes and I find this to be a perfectly acceptable solution.

The code is free to use and distribute as you would like, just give Mailmann006 a little credit if you end up using or distributing it. Thanks and enjoy!

import smtplib
import urllib
import re
import time

# Find Beginning IP at program start
url = “http://checkip.dyndns.org”
##print url
request = urllib.urlopen(url).read()
startIP = re.findall(r”d{1,3}.d{1,3}.d{1,3}.d{1,3}”, request)
##print “your start IP Address is: “,  str(startIP)

X = 1

while X == 1:

oldIP = startIP

# Find current IP
url = “http://checkip.dyndns.org”
##print url
request = urllib.urlopen(url).read()
currentIP = re.findall(r”d{1,3}.d{1,3}.d{1,3}.d{1,3}”, request)
##print “your current IP Address is: “,  str(currentIP)

# Compare old IP to current IP
if str(oldIP) != str(currentIP):
fromaddr = ‘thelairdotme@gmail.com’
toaddrs  = ‘thelairdotme@gmail.com’
msg = ‘Your I.P. has changed to ‘+ str(currentIP) +’. Make sure to update @ address in GoDaddy DNS setup!’

# Credentials for Gmail
username = ‘thelairdotme’
password = ‘**********’

# The actual mail send
server = smtplib.SMTP(‘smtp.gmail.com:587’)
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(toaddrs, fromaddr, msg)
server.quit()

# Update
startIP = currentIP

# Wait 15 minutes between checks
time.sleep(900)