import json
import time
import urllib.request
API_TOKEN = "HL.............-BqI"
ZONE_ID = "17.................20"
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 = {
"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,
"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:
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)
if __name__ == "__main__":
main()