Skip to content

Instantly share code, notes, and snippets.

@MarkZhangTW
Created April 3, 2020 14:26
Show Gist options
  • Select an option

  • Save MarkZhangTW/2d40fb552ed8d11a88e4640efba21981 to your computer and use it in GitHub Desktop.

Select an option

Save MarkZhangTW/2d40fb552ed8d11a88e4640efba21981 to your computer and use it in GitHub Desktop.
Update CloudFlare DDNS by Python
#!/usr/bin/env python3
import requests
import json
from datetime import datetime
ip = requests.get('https://icanhazip.com').text.strip()
cf_endpoint = 'https://api.cloudflare.com/client/v4/'
cf_apitoken = 'Bearer <Your API Token>'
# You can get <zone id> on CloudFlare dashboard
cf_object = 'zones/<zone id>/dns_records/<record id>'
# You can get <record id> by
# requests.get(cf_endpoint + 'zones/<zone id>/dns_records/', headers=headers).json()
url = cf_endpoint + cf_object
headers = {
'Authorization': cf_apitoken,
'Content-Type': 'application/json',
}
data = {
'type': 'A',
'name': 'example.com',
'content': ip,
'ttl': 120,
}
cf_ip = requests.get(url, headers=headers).json()['result']['content']
print(datetime.now().strftime('[%Y-%m-%d %H:%M:%S]: '), end='')
if cf_ip == ip:
print("Already up to date")
exit(0)
response = requests.put(url, headers=headers, data=json.dumps(data))
result = response.json()
success = result['success']
if success:
print("Update successfully")
else:
print("Update failed")
print(json.dumps(result, indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment