Cloudflare detail credentials = { "accountId" = "66cd45876e2985326d439", "token"=…
- User
Cloudflare detail
credentials = { "accountId" = "66cd45876e2985326d439", "token"= "9rdS_iQ4GexfUDlfCHPzbuJqRA" }
record = { "zone" = "34e2aa3dcffe9d2cb2df24460”, dynamaic = [ { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "yun"}, { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "jelly"}, { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "wire"}, { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "note"} ]
static = [ { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "gate"} ]}
create a python script to read the above settings. Then check the current external ip and compare with the cloudflare record using te credentials provided. If the exteranl ip was updated by the isp, using the cloudflare api to update each of the ip of the records according to the dynamic array. As for the static array, only need to check if it exists and insert the new record if it doesn't
- Assistant
To create a Python script that handles the requirements you've outlined, we'll need to use the
requestslibrary to interact with the Cloudflare API. Below is a Python script that checks the current external IP, compares it with the existing Cloudflare records in the dynamic array, and updates them if necessary. It also checks for static records and adds them if they do not exist.Make sure you have the
requestslibrary installed. You can install it using pip if you haven't done so:pip install requestsHere’s the Python script:
import requests import json import socket # Cloudflare credentials and record settings credentials = { "accountId": "66cd45876e2985326d439", "token": "9rdS_iQ4GexfUDlfCHPzbuJqRA" } record = { "zone": "34e2aa3dcffe9d2cb2df24460", "dynamic": [ {"domain": "marco-leong.com", "ttl": 1800, "type": "A", "name": "yun"}, {"domain": "marco-leong.com", "ttl": 1800, "type": "A", "name": "jelly"}, {"domain": "marco-leong.com", "ttl": 1800, "type": "A", "name": "wire"}, {"domain": "marco-leong.com", "ttl": 1800, "type": "A", "name": "note"} ], "static": [ {"domain": "marco-leong.com", "ttl": 1800, "type": "A", "name": "gate"} ] } # Get current external IP address def get_external_ip(): try: response = requests.get('https://api.ipify.org?format=json') return response.json()['ip'] except Exception as e: print(f"Error obtaining external IP: {e}") return None # Get current DNS records from Cloudflare def get_dns_records(zone_id): url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records" headers = { "Authorization": f"Bearer {credentials['token']}", "Content-Type": "application/json" } response = requests.get(url, headers=headers) if response.status_code == 200: return response.json()['result'] else: print(f"Error fetching DNS records: {response.text}") return [] # Update DNS record in Cloudflare def update_dns_record(zone_id, record_id, ip): url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}" data = { "type": "A", "name": record['name'], "content": ip, "ttl": record['ttl'], "proxied": False } headers = { "Authorization": f"Bearer {credentials['token']}", "Content-Type": "application/json" } response = requests.put(url, headers=headers, data=json.dumps(data)) if response.status_code == 200: print(f"Updated DNS record: {record['name']} with IP: {ip}") else: print(f"Error updating DNS record: {response.text}") # Add DNS record to Cloudflare def add_dns_record(zone_id, record): url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records" data = { "type": record['type'], "name": record['name'], "content": record['content'], "ttl": record['ttl'], "proxied": False } headers = { "Authorization": f"Bearer {credentials['token']}", "Content-Type": "application/json" } response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 200: print(f"Added DNS record: {record['name']} with IP: {record['content']}") else: print(f"Error adding DNS record: {response.text}") # Main logic def main(): external_ip = get_external_ip() if not external_ip: return zone_id = record['zone'] current_dns_records = get_dns_records(zone_id) # Dictionary of existing records for easy access existing_records = {item['name']: item for item in current_dns_records} # Check dynamic records for dynamic_record in record['dynamic']: name = dynamic_record['name'] if name in existing_records: current_ip = existing_records[name]['content'] if current_ip != external_ip: update_dns_record(zone_id, existing_records[name]['id'], external_ip) else: # Add new dynamic record dynamic_record['content'] = external_ip add_dns_record(zone_id, dynamic_record) # Check static records for static_record in record['static']: name = static_record['name'] if name not in existing_records: static_record['content'] = external_ip # You can provide any specific IP for static record add_dns_record(zone_id, static_record) if __name__ == "__main__": main()Explanation of the Script:
- Get External IP: The script fetches the current external IP using
api.ipify.org. - Get DNS Records: It retrieves current DNS records from Cloudflare for the specified zone ID.
- Update DNS Records: It checks each dynamic DNS record. If the current external IP differs from the Cloudflare record, it updates it.
- Add DNS Records: If a dynamic or static DNS record doesn’t exist, it adds the new record to Cloudflare.
- Main Function: It orchestrates the functionality by calling the necessary functions.
Note:
- Always ensure to handle sensitive credentials securely. Avoid hardcoding and use environment variables or secure storage when possible.
- Test this script in a safe environment before deploying it in production as it modifies DNS records directly.
- Get External IP: The script fetches the current external IP using