refactor(repo): most of these scripts are outdated, refactored desec
All checks were successful
/ test (push) Successful in 23s

This commit is contained in:
devaine 2026-03-05 01:06:55 -06:00
commit 6682679493
Signed by: devaine
GPG key ID: 954B1DCAC6FF84EE
18 changed files with 154 additions and 133 deletions

View file

@ -0,0 +1,127 @@
#!/usr/bin/env python
import os
from time import sleep
from dotenv import load_dotenv
import requests
load_dotenv()
# Constants
DOMAIN = os.getenv("CURRENT_DOMAIN")
DESEC_TOKEN = os.getenv("DESEC_TOKEN")
IGNORED_SUBDOMAINS_PREFIXES = ["mail._domainkey.mail", "mail", "_dmarc.mail", "skyguy"]
TIMEOUT = 10 # In seconds, 600 = 10min, 900 = 15m, 1800 = 30min
# Credits:
# https://desec.readthedocs.io/en/latest/dns/rrsets.html#modifying-an-rrset
# for documentation
def getSubDomains():
subDomainsLink = "https://desec.io/api/v1/domains/" + DOMAIN + "/rrsets/"
subDomainsHeader = {"Authorization": "Token " + DESEC_TOKEN}
subDomainsRequest = requests.get(subDomainsLink, headers=subDomainsHeader)
subDomainsJSON = subDomainsRequest.json()
return subDomainsJSON
def filterRecords():
filtered_prefixes = []
getRequestIP = requests.get("https://ifconfig.me")
requestIP = getRequestIP.text
IGNORED_SUBDOMAINS = []
for i in range(len(IGNORED_SUBDOMAINS_PREFIXES)):
IGNORED_SUBDOMAINS.append(IGNORED_SUBDOMAINS_PREFIXES[i] + "." + DOMAIN + ".")
for rrset in getSubDomains():
IS_NOT_IGNORED = rrset["name"] not in IGNORED_SUBDOMAINS
CONTAINS_A_RECORD = rrset["type"] == "A"
NOT_CURRENT_IP = rrset["records"][0] != requestIP
if IS_NOT_IGNORED and CONTAINS_A_RECORD and NOT_CURRENT_IP:
filtered_prefixes.append(rrset["subname"])
if len(filtered_prefixes) > 0:
return filtered_prefixes
def changeRecords():
prefixes = filterRecords()
# If there are no outdated subdomains...
if prefixes is None:
print("No available subdomains to change")
return
getRequestIP = requests.get("https://ifconfig.me")
requestIP = getRequestIP.text
for prefix in prefixes:
subDomainsLink = (
"https://desec.io/api/v1/domains/" + DOMAIN + "/rrsets/" + prefix + "/A/"
)
subDomainsHeader = {
"Authorization": "Token " + DESEC_TOKEN,
"Content-Type": "application/json",
}
subDomainsData = {
"subname": prefix,
"type": "A",
"records": [requestIP],
"ttl": 3600,
}
changeSubDomainRequest = requests.put(
subDomainsLink, json=subDomainsData, headers=subDomainsHeader
)
print("for prefix: " + prefix)
print(changeSubDomainRequest.text)
sleep(3)
def checkIP():
if not os.path.exists("data"):
os.mknod("data")
dataFile = open("data", "r")
getRequestIP = requests.get("https://ifconfig.me")
requestIP = getRequestIP.text
dataFileIP = dataFile.readline().replace("\n", "")
if requestIP != dataFileIP:
changeRecords()
with open("data", "w") as dataFile:
dataFile.write(requestIP)
def checkInternet():
print("Checking Connection...")
try:
testRequest = requests.get("https://ifconfig.me", timeout=15)
except (requests.Timeout, requests.ConnectionError) as exception:
print("Connection Failed!\nReason: " + exception)
checkInternet()
if testRequest.text is not None:
return True
def main():
print("Starting Script")
while checkInternet():
checkIP()
sleep(TIMEOUT)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,13 @@
#!/bin/bash
# If virtual environment does exist..
if [ ! -d venv ]; then
python3 -m venv venv
source venv/bin/activate
pip install -U python-dotenv requests
pip install -U pip # Update pip to the latest version
else
source venv/bin/activate
fi
python main.py

View file

@ -1,114 +0,0 @@
#!/usr/bin/env python
import subprocess
import json
import os
import asyncio
from time import sleep
from dotenv import load_dotenv
import urllib3
load_dotenv() # Loads up .env file
current_domain = os.getenv("CURRENT_DOMAIN")
desec_token = os.getenv("DESEC_TOKEN")
excluded_subdomains = ["mail._domainkey.mail", "mail", "_dmarc.mail"]
timeout = 1800 # In seconds, 600 = 10min, 900 = 15m, 1800 = 30min
# Credits:
# https://desec.readthedocs.io/en/latest/dns/rrsets.html#modifying-an-rrset
# for documentation
async def modifyRecords(newIP):
args = "curl https://desec.io/api/v1/domains/" + current_domain + \
"/rrsets/ --header 'Authorization: Token " + desec_token + "'"
data_binary = subprocess.run(
args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
data = data_binary.stdout.decode("utf-8")
# convert to python object from str
json_data = json.loads(data)
for i in range(len(excluded_subdomains)):
excluded_subdomains[i] = excluded_subdomains[i] + \
"." + current_domain + "."
for entry in json_data:
# Only allow "A" record subdomains at the moment
if entry["name"] not in excluded_subdomains and entry["type"] == "A":
if (entry["records"][0] != newIP):
subname = str(entry["subname"]) # Subdomain Name
# Basically runs a PATCH method for the api to change
# the ip record of all "A" record subdomains to the new
# public ip address
change_record_arg = \
"curl -X PATCH https://desec.io/api/v1/domains/" + \
current_domain + "/rrsets/" + subname + \
"/A/" + " --header 'Authorization: Token " \
+ desec_token + "'" + " --header " + \
"'Content-Type: application/json' " + \
"--data @- <<< '{\"records\": [\"" + newIP + "\"] }'"
# print(change_record_arg)
subprocess.run(change_record_arg, shell=True)
await asyncio.sleep(5)
print("done with changing records!")
def getCurrentIP():
print("getting current ip...")
# Get the current Public IP to a "public_ip" file
subprocess.run(
["curl", "ifconfig.me", "-o", "public_ip"], stderr=subprocess.DEVNULL)
async def newIPCheck():
print("checking for new ips...")
presentIPFile = open("public_ip", "r")
newIP_curl = subprocess.run(["curl", "ifconfig.me"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
newIP = newIP_curl.stdout.decode("utf-8")
if (presentIPFile.readline() == newIP):
await asyncio.sleep(timeout)
await newIPCheck()
else:
print("uh oh! public ip updated!")
await modifyRecords(newIP)
getCurrentIP() # update current ip
await newIPCheck()
def waitForConnection():
while True:
try:
response = urllib3.request("GET", "https://ifconfig.me")
return
except urllib3.exceptions.MaxRetryError:
print("Failed connection!")
sleep(1)
pass
def main():
waitForConnection()
if not os.path.exists("public_ip"):
getCurrentIP()
elif not os.path.exists(".env"):
print("no visible .env file for token!")
exit(1)
asyncio.run(newIPCheck())
if __name__ == "__main__":
main()

View file

@ -1,11 +0,0 @@
#!/bin/bash
# If virtual environment does exist..
if [ ! -d .venv ]; then
python3 -m venv .venv
source .venv/bin/activate
pip install -U python-dotenv urllib3
pip install -U pip # Update pip to the latest version
fi
echo 'Make sure to run ". .venv/bin/activate" to enter the development environment'

View file

@ -1,7 +0,0 @@
#!/bin/bash
cd /home/user/scripts/desec
. .venv/bin/activate
./desec.py