Skip to content

Instantly share code, notes, and snippets.

@altmind
Created May 30, 2021 23:43
Show Gist options
  • Save altmind/d32d6efdf37da0b49d6c6e1d644e5f8d to your computer and use it in GitHub Desktop.
Save altmind/d32d6efdf37da0b49d6c6e1d644e5f8d to your computer and use it in GitHub Desktop.
update-dns.py cloudflare ddns
#!/usr/bin/python3
import json
import socket
import sys
import urllib.request
host = sys.argv[1] if (len(sys.argv) >= 2) else socket.gethostname()
target_hostname = "%s.sub.yournet.com" % host
zone_id = "REMOVEDREMOVEDREMOVED"
token = "REMOVEDREMOVEDREMOVED"
cf_headers = {
"Authorization": "Bearer %s" % token, "Content-Type": "application/json", "User-Agent": "curl/7.68.0"}
def dl(url, headers={}, data=None, method="GET"):
rq = urllib.request.Request(url, data, headers, method=method)
with urllib.request.urlopen(rq, timeout=10) as rs:
return str(rs.read(), "utf-8")
def wrapExc(code):
try:
return code()
except:
return None
my_ip = dl("http://ifconfig.co", headers={"User-Agent": "curl/7.68.0"}).strip()
assigned_ip = wrapExc(lambda: socket.gethostbyname(target_hostname))
if my_ip != assigned_ip:
rec = json.loads(
dl("https://api.cloudflare.com/client/v4/zones/%s/dns_records?type=A&name=%s" % (zone_id, target_hostname),
headers=cf_headers))
record_id = rec["result"][0]["id"] if len(rec["result"]) >= 1 else None
req = "{\"type\":\"A\",\"name\":\"%s\",\"content\":\"%s\",\"ttl\":120,\"proxied\":false}" % (
target_hostname, my_ip)
print(req)
upd_response = dl("https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s" % (zone_id, record_id),
data=req.encode("utf-8"),
headers=cf_headers,
method="PUT")
print(upd_response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment