Created
June 2, 2023 19:51
-
-
Save JuniYadi/1c3d1d92414363024f05cb57dd23371d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
import os | |
def updateRecord(target, cf_token, ip): | |
# Cloudflare Token | |
cf_api = "https://api.cloudflare.com/client/v4/" | |
# Cloudflare Headers | |
headers = {"Authorization": "Bearer " + cf_token, | |
"Content-Type": "application/json"} | |
# Parse Main Domain | |
subdomain = target.split(".")[0] | |
domain = target.replace(subdomain + ".", "") | |
# Get ZoneID Based On Domain | |
zones = requests.get( | |
cf_api + "zones?name=" + domain, headers=headers) | |
zoneId = zones.json()["result"][0]["id"] | |
# Get RecordID Based On Subdomain | |
records = requests.get( | |
cf_api + "zones/" + zoneId + "/dns_records", headers=headers, params={"name": target}) | |
recordId = records.json()["result"][0]["id"] | |
# Update IP | |
data = {"id": recordId, "type": "A", | |
"name": target, "content": ip, "proxied": True} | |
update = requests.put( | |
cf_api + "zones/" + zoneId + "/dns_records/" + recordId, headers=headers, data=json.dumps(data)) | |
print("Update Domain {} with {}".format(target, ip)) | |
print(update.status_code) | |
def checkIP(): | |
home = os.path.expanduser("~") | |
temp = home + "/ddns-ip.txt" | |
# Get Public IP | |
ip = requests.get("http://ipinfo.io/ip").text | |
# Check if temp is exist or not | |
# If Exist, Check if IP is same or not | |
# If Same, Do Nothing | |
# If Not, Update IP | |
if os.path.isfile(temp): | |
with open(temp, "r") as f: | |
if f.read() == ip: | |
print("Skip Update, Because IP is Same. IP: " + ip) | |
return False | |
else: | |
with open(temp, "w") as f: | |
f.write(ip) | |
print("Update IP. New IP Detected. IP: " + ip) | |
return ip | |
# If temp is not exist, Create temp and write IP | |
with open(temp, "w") as f: | |
f.write(ip) | |
print("Create temp and write IP. IP: " + ip) | |
return ip | |
cf_token = "xxxxxxxx" | |
target = "ddns.example.com" | |
ip = checkIP() | |
if ip: | |
updateRecord(target, cf_token, ip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment