Skip to content

Instantly share code, notes, and snippets.

@talalashraf
Created April 13, 2023 15:50
Show Gist options
  • Save talalashraf/4d19b7531c67e576dc970da727af8451 to your computer and use it in GitHub Desktop.
Save talalashraf/4d19b7531c67e576dc970da727af8451 to your computer and use it in GitHub Desktop.
Update DNS with Fresh IP in Python
import time
import requests
import json
# Define your Cloudflare API credentials and zone details
api_key = "YOUR_API_KEY"
email = "YOUR_EMAIL"
zone_id = "YOUR_ZONE_ID"
dns_record_name = "YOUR_DNS_RECORD_NAME"
# Define a function to fetch your current public IP address
def get_public_ip():
ip_url = 'https://api.ipify.org'
response = requests.get(ip_url)
return response.text
# Define a function to get your DNS record's current IP address in Cloudflare
def get_dns_record_ip():
headers = {'X-Auth-Email': email, 'X-Auth-Key': api_key, 'Content-Type': 'application/json'}
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records?type=A&name={dns_record_name}"
response = requests.get(url, headers=headers)
dns_record = json.loads(response.text)['result'][0]
return dns_record['content']
# Define a function to update your Cloudflare DNS record with a new IP address
def update_dns_record_ip(new_ip):
headers = {'X-Auth-Email': email, 'X-Auth-Key': api_key, 'Content-Type': 'application/json'}
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{dns_record_id}"
data = {"type": "A", "name": dns_record_name, "content": new_ip}
response = requests.put(url, headers=headers, data=json.dumps(data))
print(response.text)
# Get the ID of the DNS record in Cloudflare
dns_record_id = json.loads(requests.get(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records?type=A&name={dns_record_name}", headers={'X-Auth-Email': email, 'X-Auth-Key': api_key, 'Content-Type': 'application/json'}).text)['result'][0]['id']
while True:
# Check if the current public IP address is the same as the DNS record IP in Cloudflare
current_ip = get_public_ip()
dns_record_ip = get_dns_record_ip()
if current_ip == dns_record_ip:
print("IP addresses are the same. No action needed.")
else:
# Update the DNS record with the new IP address
update_dns_record_ip(current_ip)
print("DNS record updated with new IP address.")
# Wait for 1 minute before checking again
time.sleep(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment