mitsake

Adding more stuff to the web

Dynamic DNS using the NearlyFreeSpeech.NET API (take two)


Tags: programming, python

A few years ago, I hacked together a way to updating my DNS record when my home IP changed. The script I wrote has generally been working ok, though recently I started seeing a few more errors than usual. Rather than debug them, I decided to rewrite the script using the more up-to-date python-nfsn and Requests libraries.

Both libraries are available via pip, so getting them is super-easy:

pip install python-nfsn requests # sudo was required for my particular setup

The two new libraries make the script a bit easier to read, particularly the line that gets the current external IP. I’ve switched to using ipify to do this, which means a regular expression isn’t needed anymore.

#!/usr/bin/env python

from nfsn import Nfsn
import requests
from time import strftime, localtime

user = "user" # Your NFSN username (not the one used to ssh into your site)
key = "api_key" # API key (contact NFSN support for one - it's a free request)
domain = "example.com" # Your NFS-hosted domain
subdomain = "subdomain" # The subdomain you're setting up for dynamic DNS

nfsn = Nfsn(user, key)	# Create the NFSN API object

currentip = requests.get('http://api.ipify.org').text
listedip = nfsn.dns(domain).listRRs(subdomain)[0]['data']
logtime = strftime("%Y-%m-%d %H%M", localtime())

if currentip != listedip:	# Check to see if we need to update the record; if so:
	nfsn.dns(domain).removeRR(subdomain, 'A', listedip)	# a) remove the old entry,
	nfsn.dns(domain).addRR(subdomain, 'A', currentip)	# b) add a new entry with the new IP
	print (logtime + " DNS record updated from " + listedip + " to " + currentip)
else:
	print (logtime + " No update required.")

After making the script executable and setting it to run every few hours using cron, the script seems to be running well - hopefully it works for someone else out there too.