Skip to content

Instantly share code, notes, and snippets.

@manio143
Created January 19, 2019 13:21
Show Gist options
  • Save manio143/ffd6f6451b468cb4fde8eaa1969d3c2e to your computer and use it in GitHub Desktop.
Save manio143/ffd6f6451b468cb4fde8eaa1969d3c2e to your computer and use it in GitHub Desktop.
A nice script to auto update DNS records in CloudFlare
#!/usr/bin/env python3
import requests
import json
import subprocess
home = "/home/manio/"
authKey = ""
email = ""
currentIp = subprocess.run([home+'/ip6'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
lastIp = subprocess.run(['cat', home+'/lastIp'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
print("Current IPv6 = " + currentIp);
print("Previous IPv6 = " + lastIp);
def update(zone, domain):
header = {"X-Auth-Key": authKey, "X-Auth-Email": email, "Content-Type":"application/json"}
req = requests.get("https://api.cloudflare.com/client/v4/zones/", headers=header)
zones = req.json()
for result in zones["result"]:
if(result["name"] == zone):
print("Connected to zone "+result["name"])
req = requests.get("https://api.cloudflare.com/client/v4/zones/"+result["id"]+"/dns_records?type=AAAA", headers=header)
for dns in req.json()["result"]:
print("Checking dns record "+dns["name"])
if(dns["name"].startswith(domain)):
d = json.dumps({"type":"AAAA", "name":dns["name"], "content":currentIp})
req = requests.put("https://api.cloudflare.com/client/v4/zones/"+result["id"]+"/dns_records/"+dns["id"], headers=header, data=d)
print(req.json())
if req.status_code == 200 :
print("Succesfully updated DNS record")
with open(home+"lastIp", "w") as file:
file.write(currentIp)
if(currentIp == ""):
print("No IP has been provided")
exit()
if(currentIp != lastIp):
print("Ip has changed!")
print("Updating DNS...")
update("example.com", "www.")
else:
print("Ip has not been changed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment