82 lignes
3.1 KiB
Python
82 lignes
3.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Ajoute l'enregistrement A beta.jobrunner.fr via l'API Infomaniak (à lancer sur cornafsuisse).
|
|
|
|
Le jeton est lu dans ~/.config/infomaniak/api_token, jamais affiché ni écrit ailleurs.
|
|
Mode par défaut : lecture seule + sauvegarde de la zone. --ajouter pour créer la ligne.
|
|
"""
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
DOMAINE = "jobrunner.fr"
|
|
SOURCE = "beta"
|
|
CIBLE = "179.237.102.233"
|
|
TTL = 300
|
|
BASE = "https://api.infomaniak.com/2"
|
|
|
|
|
|
def appel(methode, chemin, jeton, corps=None):
|
|
donnees = json.dumps(corps).encode() if corps is not None else None
|
|
req = urllib.request.Request(BASE + chemin, data=donnees, method=methode)
|
|
req.add_header("Authorization", "Bearer " + jeton)
|
|
req.add_header("Accept", "application/json")
|
|
if donnees is not None:
|
|
req.add_header("Content-Type", "application/json")
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=20) as r:
|
|
return json.loads(r.read().decode())
|
|
except urllib.error.HTTPError as e:
|
|
try:
|
|
return json.loads(e.read().decode())
|
|
except Exception:
|
|
return {"result": "error", "error": {"code": "http_%d" % e.code}}
|
|
|
|
|
|
def main():
|
|
ajouter = "--ajouter" in sys.argv
|
|
chemin_jeton = os.path.expanduser("~/.config/infomaniak/api_token")
|
|
with open(chemin_jeton, encoding="utf-8") as f:
|
|
jeton = f.read().strip()
|
|
|
|
zone = appel("GET", "/zones/%s/records" % DOMAINE, jeton)
|
|
if zone.get("result") != "success":
|
|
print("Erreur API (lecture) :", (zone.get("error") or {}).get("description") or (zone.get("error") or {}).get("code"))
|
|
return 1
|
|
|
|
dossier = os.path.expanduser("~/sauvegardes/dns")
|
|
os.makedirs(dossier, exist_ok=True)
|
|
nom = os.path.join(dossier, "zone-avant-jobrunner-beta-%s.json" % time.strftime("%Y%m%d-%H%M%S"))
|
|
with open(nom, "w", encoding="utf-8") as f:
|
|
json.dump(zone, f, ensure_ascii=False, indent=1)
|
|
os.chmod(nom, 0o600)
|
|
print("Sauvegarde de la zone :", nom, "(%d enregistrements)" % len(zone["data"]))
|
|
|
|
existants = [r for r in zone["data"] if r.get("source") == SOURCE]
|
|
print("Lignes A de la zone :")
|
|
for r in zone["data"]:
|
|
if r.get("type") == "A":
|
|
src = "@" if r.get("source") in ("", ".") else r.get("source")
|
|
print(" A %-12s -> %s (ttl %s)" % (src, r.get("target"), r.get("ttl")))
|
|
if existants:
|
|
print("Une ligne '%s' existe déjà :" % SOURCE, [(r["type"], r["target"]) for r in existants])
|
|
return 0
|
|
|
|
if not ajouter:
|
|
print("Simulation : '%s' absent. Relance avec --ajouter pour créer A %s -> %s." % (SOURCE, SOURCE, CIBLE))
|
|
return 0
|
|
|
|
rep = appel("POST", "/zones/%s/records" % DOMAINE, jeton,
|
|
{"type": "A", "source": SOURCE, "target": CIBLE, "ttl": TTL})
|
|
if rep.get("result") == "success":
|
|
print("OK : A %s.%s -> %s créé." % (SOURCE, DOMAINE, CIBLE))
|
|
return 0
|
|
print("Erreur API (création) :", (rep.get("error") or {}).get("description") or (rep.get("error") or {}).get("code"))
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|