A Python script that contacts the CloudFlare v4 API to retrieve zone details and updates a subdomain A record with your current public IPv4 address.
Before calling this script, edit it to include your API email, key, and default record to update (I suggest test.yourdomain.com or similar). Usage:
python /path/to/script.py [subdomain [yourdomain.com]]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | #!/usr/bin/python import sys, urllib2, json # Update email address and key with API details # https://www.cloudflare.com/a/account/my-account cfheader={'X-Auth-Email' : 'youremail@yourdomain.com', 'X-Auth-Key' : 'replace_with_your_api_key', 'Content-type' : 'application/json'} # Modify these to set the 'default' domain to update sd=sys.argv[1] if len(sys.argv)>1 else 'subdomain' dn=sys.argv[2] if len(sys.argv)>2 else 'yourdomain.com' # The rest of the script does not need to be modified cfurl='https://api.cloudflare.com/client/v4/zones/' ipurl='http://ipinfo.io/ip' apirec='/dns_records/' myip=None cfip=None dnid=None sdid=None fqdn=sd+'.'+dn try: print 'Checking our public IP...', uaheader={'User-Agent' : 'Magic Browser'} req=urllib2.Request(ipurl,headers=uaheader) myip=urllib2.urlopen(req).read() print 'Got %s.' %myip except urllib2.URLError as e: print 'Problem getting our IP.' print e exit(0) try: print 'Checking Cloudflare for %s...' %dn, req=urllib2.Request(cfurl,headers=cfheader) strjson=urllib2.urlopen(req).read() for d in json.loads(strjson)['result']: if d['name']==dn: dnid=d['id'] print 'OK.' try: print 'Checking %s...' %fqdn, req=urllib2.Request(cfurl+dnid+apirec,headers=cfheader) strjson=urllib2.urlopen(req).read() for h in json.loads(strjson)['result']: if h['name']==fqdn and h['type']=='A': sdid=h['id'] cfip=h['content'] print 'Got %s.' %cfip except urllib2.HTTPError as e: print 'Could not retrieve host ID for %s' %sd print e exit(0) if dnid==None or cfip==None: print 'No data found.' except urllib2.HTTPError as e: print 'Could not retrieve zone ID for %s ' %dn print e exit(0) if cfip==None: print 'Unable to update - missing Cloudflare IP.' elif myip==None: print 'Unable to update - missing our public IP.' elif myip==cfip: print 'Update not required.' else: try: update=json.dumps({'id' : sdid, 'type' : 'A', 'name' : sd, 'content' : myip}) req=urllib2.Request(cfurl+dnid+apirec+sdid,data=update,headers=cfheader) req.get_method=lambda:'PUT' if json.loads(urllib2.urlopen(req).read())['success']: print 'Update successful.' except urllib2.HTTPError as e: print 'Could not update Cloudflare.' print e |