Hostinger-DDNS/main.py

61 lines
No EOL
2 KiB
Python

import requests, os, time
from dotenv import load_dotenv
while True:
load_dotenv()
#Enviroment variables.
DOMAIN = os.getenv("DOMAIN")
SUBDOMAIN = os.getenv("SUBDOMAIN")
DNS_RECORD_TYPE = os.getenv("DNS_RECORD_TYPE")
TOKEN = os.getenv("TOKEN")
#Internal variables.
public_ip = requests.get("https://api.ipify.org/").text.strip() #The public IP of the container.
dns_ip = None #The current IP of the DNS record, unpopulated.
#Set the proper headers.
headers = {
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json"
}
#Get the zone using the token and domain.
zone = (requests.get(
f"https://developers.hostinger.com/api/dns/v1/zones/{DOMAIN}",
headers=headers).json())
#Get the current DNS record, and set it to the dns_ip variable.
for record in zone:
if record["name"] == SUBDOMAIN and record["type"] == DNS_RECORD_TYPE:
dns_ip = record["records"][0]["content"]
if dns_ip == public_ip:
#No action needed.
print("Values are the same, no need to update DNS record.")
elif dns_ip != public_ip:
#Step 1: Notify the user that the value is different.
print("DNS record is different, modifying DNS record...")
print("Current DNS value is:", dns_ip)
#Step 2: Set the value to the new public IP.
for record in zone:
if record["name"] == SUBDOMAIN and record["type"] == DNS_RECORD_TYPE:
if record.get("records"):
record["records"][0]["content"] = public_ip
print("Updated DNS value will be:", public_ip)
#Step 3: Push the value to Hostinger.
response = requests.put(
f"https://developers.hostinger.com/api/dns/v1/zones/{DOMAIN}",
headers=headers,
json={"zone": zone}
)
#Step 4: Notify the user of the status of the response.
print("Status code:", response.status_code)
print("Response:", response.text)
time.sleep(300)