Files
inwx-scripts/inwx_add_record.py
T
2026-04-28 22:25:24 +02:00

99 lines
3.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
import sys
import os
import subprocess
import argparse
# Import-Fix für die Library-Struktur
try:
from INWX.Domrobot import ApiClient
except ImportError:
from inwx.Domrobot import ApiClient
# --- KONFIGURATION ---
API_URL = 'https://api.domrobot.com'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
KP_DB_PATH = os.path.join(BASE_DIR, "hosting.kdbx")
KP_ENTRY_NAME = "inwx"
DOMAIN = "ma151.de"
def get_creds():
"""Holt die Daten sicher aus KeePassXC."""
try:
cmd = ["keepassxc-cli", "show", "-s", KP_DB_PATH, KP_ENTRY_NAME]
output = subprocess.check_output(cmd, text=True)
creds = {}
for line in output.splitlines():
if ":" in line:
k, v = line.split(":", 1)
creds[k.strip().lower()] = v.strip()
return creds.get("username") or creds.get("benutzername"), creds.get("password") or creds.get("passwort")
except Exception as e:
print(f"❌ KeePass-Fehler: {e}")
return None, None
def main():
# 1. Argument-Parser einrichten
parser = argparse.ArgumentParser(description=f"DNS-Record zu {DOMAIN} hinzufügen.")
parser.add_argument("type", help="Typ des Records (z.B. A, AAAA, CNAME, TXT)")
parser.add_argument("name", help="Name/Subdomain (z.B. srv1)")
parser.add_argument("content", help="Wert des Records (z.B. die IP-Adresse)")
parser.add_argument("--ttl", type=int, default=3600, help="TTL in Sekunden (Standard: 3600)")
args = parser.parse_args()
# 2. Zugangsdaten laden
user, password = get_creds()
if not user or not password:
sys.exit(1)
api = ApiClient(api_url=API_URL)
# 3. Login
login_res = api.login(user, password)
if login_res['code'] != 1000:
print(f"❌ Login fehlgeschlagen: {login_res['msg']}")
sys.exit(1)
# 4. Prüfen, ob der Record existiert
full_name = f"{args.name}.{DOMAIN}"
print(f"🔍 Prüfe {full_name} ({args.type} -> {args.content})...")
info_res = api.call_api('nameserver.info', {'domain': DOMAIN})
if info_res['code'] != 1000:
print(f"❌ Fehler bei Domain-Info: {info_res['msg']}")
api.logout()
sys.exit(1)
records = info_res['resData'].get('record', [])
already_exists = False
for rec in records:
if (rec['name'].rstrip('.') == full_name and
rec['type'].upper() == args.type.upper() and
rec['content'] == args.content):
already_exists = True
break
if already_exists:
print(f"️ Record existiert bereits. Keine Aktion erforderlich.")
else:
# 5. Record erstellen
print(f"🚀 Erstelle neuen Record...")
create_res = api.call_api('nameserver.createRecord', {
'domain': DOMAIN,
'name': args.name,
'type': args.type.upper(),
'content': args.content,
'ttl': args.ttl
})
if create_res['code'] == 1000:
print(f"✅ Erfolg! Record ID: {create_res['resData']['id']}")
else:
print(f"❌ Fehler: {create_res['msg']} (Code: {create_res['code']})")
api.logout()
if __name__ == "__main__":
main()