Created
January 19, 2016 07:08
-
-
Save m3nu/62ffc2d402166f3e0694 to your computer and use it in GitHub Desktop.
Python Cloudflare Dynamic DNS Update script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Update Cloudflare zone entry to current external IP. | |
Works great with servers on changing IPs or AWS spot instances. | |
Usage: | |
python cloudflare_update.py subdomain | |
""" | |
import sys | |
import json | |
import requests | |
EMAIL = 'XXXXX' | |
KEY = 'XXXXXXX' | |
ZONE = 'XXXX.com' | |
RECORD = sys.argv[1] | |
CONTENT = requests.get('http://jsonip.com').json()['ip'] | |
headers = {'X-Auth-Key': KEY, 'X-Auth-Email': EMAIL, 'Content-type': 'application/json'} | |
base_url = 'https://api.cloudflare.com/client/v4{}' | |
# Get Zone ID | |
r = requests.get(base_url.format('/zones'), headers=headers) | |
for res in r.json()['result']: | |
if res['name'] == ZONE: | |
ZONE_ID = res['id'] | |
# Get list of Zone DNS records | |
RECORD_ID = None | |
url_path = '/zones/{}/dns_records'.format(ZONE_ID) | |
r = requests.get(base_url.format(url_path), headers=headers) | |
for res in r.json()['result']: | |
if res['name'] == '{}.{}'.format(RECORD, ZONE): | |
RECORD_ID = res['id'] | |
# Update or add Zone Record. | |
JSON_CONTENT = json.dumps({'type': 'A', 'name': RECORD, 'content': CONTENT}) | |
if RECORD_ID: | |
url_path = '/zones/{}/dns_records/{}'.format(ZONE_ID, RECORD_ID) | |
url = base_url.format(url_path) | |
requests.put(url, headers=headers data=JSON_CONTENT) | |
else: | |
url_path = '/zones/{}/dns_records'.format(ZONE_ID) | |
url = base_url.format(url_path) | |
requests.post(url, headers=headers, data=JSON_CONTENT) |
Hey this script only adds another A record to my Cloudflare but does not delete or alter the old one, so that I collect a lot of old entries... any idea how to fix that?
Here is a similar bash script I just wrote for my company if anyone is interested: https://github.com/MachineITSvcs/Cloudflare-DDNS-Update
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to edit line 44 to have a comma, otherwise you'll get a syntax error:
requests.put(url, headers=headers, data=JSON_CONTENT)