CloudFlare Dynamic DNS

Here’s a simple Python script that can be called with your CloudFlare credentials to update the IP address with the address of the connecting machine.

Be sure to input your own information in the Email field, API key, base domain, record type, and record name. Any comments, I’d love to hear them.

I suggest running this script as a cron job set to run every 30 minutes or so, depending on your usage. Also, it doesn’t hurt to run it with the nice command!
[Download | GitHub Repository]

#Change the following

cloudflareEmail="[email protected]" #CF Login Email Address
cloudflareAPIkey="yourlonglowercaseandnumberapikey" #API Key as shown on https://www.cloudflare.com/my-account

#the following credentials will update the A record for example.thebasedomainname.com with the IP address of the connecting machine
baseDomain='thebasedomainname.com' #Domain Name as shown on https://www.cloudflare.com/my-websites.html
recordType='A' #See "Type" Column on https://www.cloudflare.com/dns-settings?z=example.com
recordName='example' #See "Name" Column on https://www.cloudflare.com/dns-settings?z=example.com

import os,re
import urllib
import sys

#Find the CloudFlare ID of your (sub)domain based on the recordName and recordType
data={'a': 'rec_load_all','tkn': cloudflareAPIkey,'email': cloudflareEmail,'z': baseDomain}
data = urllib.urlencode(data)
f = urllib.urlopen("https://www.cloudflare.com/api_json.html", data)
recloadall=f.read()
#print recloadall
recloadall=recloadall[0:recloadall.find('"display_name":"'+str(recordName)+'","type":"'+str(recordType)+'"')]
recordID=recloadall[recloadall.rfind("rec_id")+9:recloadall.find('","',recloadall.rfind("rec_id")+9)]
#print recordID
if recordID.find(':"error"')>-1:
recordID=recordID[recordID.find('"msg":"')+6:recordID.find(",",recordID.find('"msg":"')+3)]
print "CF Record:",recordID

#Get your current device IP Address
f = urllib.urlopen("http://ip-api.com/xml")
ipe=f.read()
ip=ipe[ipe.find("< ![CDATA[")+16:ipe.rfind("]]>",ipe.find("< ![CDATA["))].strip() print "IP Address:",ip #Update with Cloudflare data={'a': 'rec_edit','tkn': cloudflareAPIkey,'id': recordID,'email': cloudflareEmail,'z': baseDomain,'type': recordType,'name': recordName,'content': ip,'service_mode': '0','ttl': '1'} data = urllib.urlencode(data) f = urllib.urlopen("https://www.cloudflare.com/api_json.html", data) response=f.read() #print response print "Update:",response[response.find('result":')+9:response.find(',',response.find('result":')+3)-1]

Cheers!

2 thoughts on “CloudFlare Dynamic DNS”

  1. Hi, thanks for sharing, but I’ve got a issue, when I try to run it, always appears this error.

    CF Record: 157214809″,”rec_hash”:”7773f8d05bb3ec05e94caf1d8b5b774e”,”zone_name”:”ggarza.tk”,”name”:”www.ggarza.
    IP Address: 187.138.142.125
    Update: error

    Thank you!

    Reply

Leave a Comment