Skip to content

Instantly share code, notes, and snippets.

@kyujin-cho
Last active May 9, 2020 04:38
Show Gist options
  • Save kyujin-cho/ab0a3e812a9a1eb31736e79a7f9d9108 to your computer and use it in GitHub Desktop.
Save kyujin-cho/ab0a3e812a9a1eb31736e79a7f9d9108 to your computer and use it in GitHub Desktop.
CloudFlare DDNS script with Python
import requests
import CloudFlare
import os
from dotenv import load_dotenv
load_dotenv(verbose=True)
zone_name = os.environ['CF_ZONE_NAME']
dns_name = os.environ['CF_RECORD_NAME']
my_ip = res = requests.get('https://ipconfig.io', headers={'User-Agent': 'curl'}).text.strip()
cf = CloudFlare.CloudFlare()
zone_info = cf.zones.get(params={'name': zone_name})
zone_id = zone_info[0]['id']
dns_records = cf.zones.dns_records.get(zone_id, params={'name':dns_name + '.' + zone_name, type: 'A'})
body = {'type': 'A', 'name': f'{dns_name}.{zone_name}', 'content': my_ip, 'ttl': 1, 'proxied': False}
if len(dns_records) == 0:
r = cf.zones.dns_records.post(zone_id, data=body)
else:
r = cf.zones.dns_records.put(zone_id, dns_records[0]['id'], data=body)
print(r)
#!/bin/sh
export PATH=~/.pyenv/shims:~/.pyenv/bin:"$PATH"
export CF_API_KEY=<API Key>
export CF_ZONE_NAME=<Zone Name>
export CF_RECORD_NAME=<Record Name>
curdir=`pwd`
cd "$(dirname "$0")"
python update.py
cd $curdir
@kyujin-cho
Copy link
Author

  • Required permissions(scopes) for API Key

Screen Shot 2020-05-09 at 1 35 12 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment