1. DynamicDNS.py

import json
import time
import urllib.request
# Cloudflare API token
API_TOKEN = "HL.............-BqI"
ZONE_ID = "17.................20"  # Assuming all records are in the same zone
# List of DNS records to update
DNS_RECORDS = [
   {
       "record_id": "bb...............bf",
       "record_name": "subdomain1.domain.com",
       "record_type": "A",
       "proxy": True
   },
   {
       "record_id": "bb...............bf",
       "record_name": "subdomain2.domain.com",
       "record_type": "A",
       "proxy": True
   },
]
# Headers for Cloudflare API authentication
headers = {
   "Authorization": f"Bearer {API_TOKEN}",
   "Content-Type": "application/json",
}
def get_public_ip():
   """Fetches the public IP address of the server."""
   try:
       with urllib.request.urlopen("https://api.ipify.org?format=json") as response:
           data = json.load(response)
           return data["ip"]
   except Exception as e:
       print(f"Error fetching public IP: {e}")
       return None
def update_dns_record(record, ip):
   """Updates the DNS record on Cloudflare with the current IP."""
   url = f"https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/dns_records/{record['record_id']}"
   data = json.dumps({
       "type": record["record_type"],
       "name": record["record_name"],
       "content": ip,
       "ttl": 300,  # Set TTL in seconds
       "proxied": record["proxy"]
   }).encode("utf-8")
   request = urllib.request.Request(url, data=data, headers=headers, method="PUT")
   try:
       with urllib.request.urlopen(request) as response:
           if response.status == 200:
               print(f"DNS record {record['record_name']} updated successfully.")
           else:
               print(f"Failed to update DNS record {record['record_name']}: Status {response.status}")
   except Exception as e:
       print(f"Error updating DNS record {record['record_name']}: {e}")
def main():
   """Main function to update DNS records every 5 minutes."""
   current_ips = {record["record_id"]: None for record in DNS_RECORDS}
   while True:
       new_ip = get_public_ip()
       if new_ip:
           for record in DNS_RECORDS:
               # Check if the IP has changed for this record
               if current_ips[record["record_id"]] != new_ip:
                   print(f"Updating DNS for {record['record_name']} to new IP: {new_ip}")
                   update_dns_record(record, new_ip)
                   current_ips[record["record_id"]] = new_ip
               else:
                   print(f"IP for {record['record_name']} has not changed, skipping update.")
       else:
           print("Could not fetch public IP, skipping updates.")
       time.sleep(300)  # Wait 5 minutes
if __name__ == "__main__":
   main()

Jozef
Author