Skip to content

Instantly share code, notes, and snippets.

@spacelatte
Created August 3, 2020 01:19
Show Gist options
  • Save spacelatte/6f591b033ffbbf3fdc223d66349cec40 to your computer and use it in GitHub Desktop.
Save spacelatte/6f591b033ffbbf3fdc223d66349cec40 to your computer and use it in GitHub Desktop.
cloudflare dynamic dns #ddns #dyndns public ip setter script
#!/usr/bin/env python3
# First create subdomain. Eg: laptop.example.com
# Then set parameters belog. Eg: subdom = "laptop"
# This script will fetch external public ip and set it as value.
# Make sure target record is A record!
import json, urllib.request
"""
urllib.request.install_opener(
urllib.request.build_opener(
urllib.request.HTTPSHandler(debuglevel=1)
)
)
"""
request = lambda url, data=None, headers={}, method="GET": \
urllib.request.urlopen(
urllib.request.Request(url, data=data, headers=headers, method=method)
).read().decode()
ident = None #"5d0351519136bf626c8c15fb2b304c84"
zone = "_your_zone_id_"
mail = "_your_mail_addr_"
apikey = "_your_api_key_"
addr = request("http://wtfismyip.com/text").split()[0]
url_r = "https://api.cloudflare.com/client/v4/zones/{zone}/dns_records"
url_w = "https://api.cloudflare.com/client/v4/zones/{zone}/dns_records/{id}"
subdom = "_subdomain_to_search_for_"
head = {
"Content-Type": "application/json",
"X-AUTH-EMAIL": mail,
"X-AUTH-KEY": apikey,
}
data = {
"ttl": 300,
"type": "A",
"name": subdom,
"content": addr,
}
resp = json.loads(request(url_r.format(zone=zone), headers=head))
if not ident: # searches for id of subdomain
for z in resp["result"]:
if z["name"].startswith(subdom):
ident = z["id"]
resp = json.loads(request(url_w.format(id=ident, zone=zone),
headers=head, data=json.dumps(data).encode(), method="PUT"
))
print(resp["result"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment