Files
NetTransfare/nettmanage.py
T
MrBlakeandClaude Opus 5.5 0f054ef109 Back up plugin files referenced by model FileFields
- Scan all Django models (incl. plugins) for FileFields via manage.py
  shell, like the NetBox-Export plugin, and use the real MEDIA_ROOT
- Store files outside MEDIA_ROOT under extra_files/ and restore them to
  their original path (mapped onto the current installation)
- Warn about missing files and files in external storages
- Bump backup format to 1.4, document in READMEs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 13:47:31 +01:00

1945 lines
74 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 json
import os
import re
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from datetime import datetime
# ==========================================
# Standard-Konfiguration
# ==========================================
CONFIG = {
"netbox_path": "/opt/netbox",
"db_host": "localhost",
"db_name": "netbox",
"db_user": "netbox",
"db_pass": "",
"backup_dir": "/tmp",
# Leer lassen, damit upgrade.sh den Standard-Python-Interpreter verwendet.
# Beispiel für NetBox 4.5/4.6: /usr/bin/python3.12
"python_path": "",
}
NETBOX_SERVICES = ("netbox", "netbox-rq")
# Diese Einträge werden beim Upgrade auf Wunsch ergänzt. Bereits vorhandene
# Einträge (auch mit Versions-Pin) werden nicht doppelt hinzugefügt.
DEFAULT_PLUGIN_REQUIREMENTS = (
"netbox-topology-views",
"netbox-attachments",
"netbox-ping",
"netbox-reorder-rack",
"netbox-secrets",
"netbox-inventory",
"git+https://git.mrblake.cc/MrBlake/NetBox-VM-Import.git#egg=netbox_vmware_importer",
)
LDAP_REQUIREMENT = "django-auth-ldap"
BACKUP_FORMAT_VERSION = "1.4"
# Relativ zum NetBox-Verzeichnis: werden nicht als Installationsdateien gesichert.
# venv und static erzeugt upgrade.sh neu, Media wird separat gesichert.
FILES_EXCLUDE_DIRS = ("venv", "netbox/media", "netbox/static")
FILES_EXCLUDE_NAMES = ("__pycache__",)
# ==========================================
# Hilfsfunktionen für die Shell-GUI
# ==========================================
class Colors:
HEADER = "\033[95m"
BLUE = "\033[94m"
GREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
def clear_screen():
os.system("clear" if os.name == "posix" else "cls")
def print_header(title):
clear_screen()
print(Colors.HEADER + Colors.BOLD + "=" * 60 + Colors.ENDC)
print(Colors.HEADER + Colors.BOLD + f" {title}".ljust(59) + Colors.ENDC)
print(Colors.HEADER + Colors.BOLD + "=" * 60 + Colors.ENDC + "\n")
def log_info(msg):
print(Colors.BLUE + f"[*] {msg}" + Colors.ENDC)
def log_success(msg):
print(Colors.GREEN + Colors.BOLD + f"[+] {msg}" + Colors.ENDC)
def log_error(msg):
print(Colors.FAIL + Colors.BOLD + f"[-] {msg}" + Colors.ENDC)
def log_warn(msg):
print(Colors.WARNING + f"[!] {msg}" + Colors.ENDC)
def pause():
input(Colors.BOLD + "\nDrücke [ENTER], um ins Hauptmenü zurückzukehren..." + Colors.ENDC)
def run_command(command, *, env=None, cwd=None, capture=False):
"""Führt einen Befehl ohne Shell aus und liefert CompletedProcess zurück."""
kwargs = {
"env": env,
"cwd": cwd,
"text": True,
"check": False,
}
if capture:
kwargs["stdout"] = subprocess.PIPE
kwargs["stderr"] = subprocess.PIPE
return subprocess.run(command, **kwargs)
def unique_path(path):
"""Erzeugt einen noch nicht belegten Pfad durch Anhängen einer Nummer."""
if not os.path.lexists(path):
return path
counter = 1
while True:
candidate = f"{path}_{counter}"
if not os.path.lexists(candidate):
return candidate
counter += 1
def safe_extract_zip(zipf, destination):
"""Verhindert Zip-Slip beim Entpacken von Backup-Dateien."""
destination_real = os.path.realpath(destination)
for member in zipf.infolist():
target = os.path.realpath(os.path.join(destination, member.filename))
if os.path.commonpath((destination_real, target)) != destination_real:
raise ValueError(f"Unsicherer ZIP-Pfad erkannt: {member.filename}")
zipf.extractall(destination)
def safe_extract_tar(tarf, destination):
"""Entpackt ein Release-Archiv ohne Pfad-Traversal oder Archiv-Symlinks."""
destination_real = os.path.realpath(destination)
for member in tarf.getmembers():
target = os.path.realpath(os.path.join(destination, member.name))
if os.path.commonpath((destination_real, target)) != destination_real:
raise ValueError(f"Unsicherer TAR-Pfad erkannt: {member.name}")
if member.issym() or member.islnk():
raise ValueError(f"Symlink/Hardlink im TAR-Archiv nicht erlaubt: {member.name}")
tarf.extractall(destination)
# ==========================================
# Kernfunktionen: Backup & Restore
# ==========================================
def execute_backup():
print_header("BACKUP PROZESS")
log_info("Konfiguriere den Backup-Umfang:")
do_db = input(" 1. Datenbank sichern? (J/n): ").strip().lower() != "n"
exclude_changelog = False
exclude_users = False
if do_db:
exclude_changelog = (
input(
Colors.BLUE
+ " -> Changelog (extras_objectchange) auslassen? Spart viel Platz. (j/N): "
+ Colors.ENDC
)
.strip()
.lower()
== "j"
)
print(
Colors.WARNING
+ " Hinweis: Das Auslassen von Benutzern kann beim Restore zu Foreign-Key-Fehlern führen, falls Objekte diesen Benutzern zugewiesen sind."
+ Colors.ENDC
)
exclude_users = (
input(
Colors.BLUE
+ " -> Benutzer (User, Gruppen, Tokens) auslassen? (j/N): "
+ Colors.ENDC
)
.strip()
.lower()
== "j"
)
do_media = input("\n 2. Media-Dateien (Bilder/Dokumente) sichern? (J/n): ").strip().lower() != "n"
do_files = (
input(
"\n 3. Installationsdateien (Konfiguration, local_requirements.txt, Skripte, "
"Reports, ...) sichern? (J/n): "
)
.strip()
.lower()
!= "n"
)
if not do_db and not do_media and not do_files:
log_warn("Keine Komponenten zum Sichern ausgewählt. Abbruch.")
pause()
return
try:
zip_file_path = create_backup(
do_db=do_db,
do_media=do_media,
do_files=do_files,
exclude_changelog=exclude_changelog,
exclude_users=exclude_users,
)
print("\n" + "=" * 60)
log_success("BACKUP ERFOLGREICH ABGESCHLOSSEN!")
log_success(f"Datei liegt hier: {zip_file_path}")
print("=" * 60)
except Exception as exc:
log_error(f"Kritischer Fehler: {exc}")
pause()
def _manifest_entry(full_path, rel_path, kind):
file_stat = os.lstat(full_path)
entry = {
"path": rel_path,
"type": kind,
"mode": stat.S_IMODE(file_stat.st_mode),
"uid": file_stat.st_uid,
"gid": file_stat.st_gid,
}
if kind == "symlink":
entry["target"] = os.readlink(full_path)
return entry
def collect_installation_files(root):
"""Sammelt alle Dateien der Installation (ohne venv, Media, static und Caches).
Liefert eine Liste (absoluter Pfad, relativer Pfad) der zu sichernden Dateien
sowie ein Manifest mit Rechten, Besitzern und Symlinks.
"""
files = []
manifest = [_manifest_entry(root, ".", "dir")]
for current, dirnames, filenames in os.walk(root, followlinks=False):
rel_dir = os.path.relpath(current, root)
rel_dir = "" if rel_dir == "." else rel_dir.replace(os.sep, "/")
kept_dirs = []
for name in sorted(dirnames):
rel_path = f"{rel_dir}/{name}" if rel_dir else name
full_path = os.path.join(current, name)
if name in FILES_EXCLUDE_NAMES or rel_path in FILES_EXCLUDE_DIRS:
continue
if os.path.islink(full_path):
manifest.append(_manifest_entry(full_path, rel_path, "symlink"))
continue
manifest.append(_manifest_entry(full_path, rel_path, "dir"))
kept_dirs.append(name)
dirnames[:] = kept_dirs
for name in sorted(filenames):
rel_path = f"{rel_dir}/{name}" if rel_dir else name
full_path = os.path.join(current, name)
if os.path.islink(full_path):
manifest.append(_manifest_entry(full_path, rel_path, "symlink"))
continue
if not os.path.isfile(full_path):
continue
manifest.append(_manifest_entry(full_path, rel_path, "file"))
files.append((full_path, rel_path))
return files, manifest
# Wird im NetBox-venv per "manage.py shell" ausgeführt (Ansatz wie im NetBox-Export-Plugin):
# alle Modelle inkl. Plugins nach FileFields durchsuchen und die echten Dateipfade ermitteln.
FILE_SCAN_CODE = r"""
import json, os
from django.apps import apps
from django.conf import settings
from django.db import models
out = {"media_root": str(settings.MEDIA_ROOT), "files": [], "missing": [], "remote": []}
for model in apps.get_models():
opts = model._meta
if opts.abstract or opts.proxy or not opts.managed:
continue
fields = [f for f in opts.concrete_fields if isinstance(f, models.FileField)]
if not fields:
continue
for obj in model._default_manager.all().only("pk", *[f.name for f in fields]).iterator():
for field in fields:
value = getattr(obj, field.name)
if not value:
continue
entry = {"model": opts.label_lower, "field": field.name, "name": str(value.name)}
try:
path = value.path
except (NotImplementedError, AttributeError):
out["remote"].append(entry)
continue
entry["path"] = os.path.realpath(path)
out["files" if os.path.isfile(path) else "missing"].append(entry)
print("@@NETTRANSFARE@@" + json.dumps(out))
"""
def scan_model_files(netbox_root):
"""Ermittelt alle von Modellen (auch Plugins) referenzierten Dateien. None, wenn nicht möglich."""
python_bin = os.path.join(netbox_root, "venv", "bin", "python")
manage_py = os.path.join(netbox_root, "netbox", "manage.py")
if not (os.path.isfile(python_bin) and os.path.isfile(manage_py)):
log_warn(" -> NetBox-venv nicht gefunden; Plugin-Dateien außerhalb von media/ werden nicht erfasst.")
return None
proc = run_command(
[python_bin, manage_py, "shell", "--no-imports", "-c", FILE_SCAN_CODE],
cwd=os.path.dirname(manage_py),
capture=True,
)
if proc.returncode != 0 and "--no-imports" in (proc.stderr or ""):
proc = run_command(
[python_bin, manage_py, "shell", "-c", FILE_SCAN_CODE],
cwd=os.path.dirname(manage_py),
capture=True,
)
for line in reversed((proc.stdout or "").splitlines()):
if line.startswith("@@NETTRANSFARE@@"):
return json.loads(line[len("@@NETTRANSFARE@@"):])
log_warn(f" -> Datei-Scan über Django fehlgeschlagen: {(proc.stderr or '').strip()[-500:]}")
return None
def is_within(path, root):
try:
return os.path.commonpath((os.path.realpath(path), os.path.realpath(root))) == os.path.realpath(root)
except ValueError:
return False
def create_backup(
do_db=True,
do_media=True,
do_files=True,
exclude_changelog=False,
exclude_users=False,
name_prefix="netbox_backup",
):
"""Erstellt ein ZIP-Backup und gibt dessen Pfad zurück. Wirft bei Fehlern eine Exception."""
netbox_root = os.path.realpath(CONFIG["netbox_path"])
media_path = os.path.join(netbox_root, "netbox", "media")
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
os.makedirs(CONFIG["backup_dir"], exist_ok=True)
zip_file_path = unique_path(os.path.join(CONFIG["backup_dir"], f"{name_prefix}_{stamp}.zip"))
tmp_dir = tempfile.mkdtemp(prefix=f"nb_tmp_{stamp}_", dir=CONFIG["backup_dir"])
zip_created = False
try:
# 1. Datenbank-Dump
dump_file = os.path.join(tmp_dir, "netbox_database.dump")
if do_db:
log_info("\nSchritt 1: Erstelle PostgreSQL-Datenbank-Dump...")
env = os.environ.copy()
if CONFIG["db_pass"]:
env["PGPASSWORD"] = CONFIG["db_pass"]
cmd = [
"pg_dump",
"-Fc",
"-h",
CONFIG["db_host"],
"-U",
CONFIG["db_user"],
"-d",
CONFIG["db_name"],
"-f",
dump_file,
]
# --exclude-table-data lässt die Tabellenstruktur intakt,
# exportiert aber keine Inhalte der gewählten Tabellen.
if exclude_changelog:
cmd.append("--exclude-table-data=extras_objectchange")
log_info(" -> Changelog-Daten werden übersprungen.")
if exclude_users:
cmd.extend(
[
"--exclude-table-data=auth_user",
"--exclude-table-data=auth_group",
"--exclude-table-data=users_token",
]
)
log_info(" -> Benutzer-Daten werden übersprungen.")
process = run_command(cmd, env=env, capture=True)
if process.returncode != 0:
log_error(f"pg_dump fehlgeschlagen: {process.stderr}")
raise RuntimeError("Datenbank-Backup fehlgeschlagen.")
log_success("PostgreSQL-Dump erfolgreich erstellt.")
else:
log_info("\nSchritt 1: Datenbank-Backup übersprungen.")
# 2. Media-Dateien
media_files = []
extra_files = []
file_scan = None
if do_media:
log_info("Schritt 2: Sammle Media-Dateien (Bilder, Dokumente, Plugin-Dateien)...")
file_scan = scan_model_files(netbox_root)
if file_scan and file_scan.get("media_root"):
media_path = os.path.realpath(file_scan["media_root"])
log_info(f" -> MEDIA_ROOT laut NetBox: {media_path}")
if os.path.isdir(media_path):
for current, _, filenames in os.walk(media_path):
for filename in filenames:
full_path = os.path.join(current, filename)
if os.path.isfile(full_path):
rel_path = os.path.relpath(full_path, media_path).replace(os.sep, "/")
media_files.append((full_path, rel_path))
log_success(f"{len(media_files)} Media-Dateien gefunden.")
else:
log_warn(f"Kein Media-Verzeichnis unter {media_path} gefunden.")
if file_scan:
seen = set()
for entry in file_scan["files"]:
path = entry["path"]
if path in seen or is_within(path, media_path):
continue
seen.add(path)
extra_files.append(path)
total = len(file_scan["files"])
log_success(
f"{total} von Modellen referenzierte Dateien geprüft, "
f"{len(extra_files)} davon liegen außerhalb von MEDIA_ROOT und werden zusätzlich gesichert."
)
for entry in file_scan["missing"][:20]:
log_warn(f" -> Datei fehlt auf der Platte: {entry['model']}.{entry['field']} = {entry['name']}")
if len(file_scan["missing"]) > 20:
log_warn(f" -> ... insgesamt {len(file_scan['missing'])} fehlende Dateien.")
if file_scan["remote"]:
log_warn(
f" -> {len(file_scan['remote'])} Dateien liegen in einem externen Storage (z. B. S3) "
"und werden nicht gesichert."
)
else:
log_info("Schritt 2: Media-Backup übersprungen.")
# 3. Installationsdateien
install_files = []
manifest = []
if do_files:
log_info(f"Schritt 3: Sammle Installationsdateien aus {netbox_root} ...")
if not os.path.isdir(netbox_root):
raise RuntimeError(f"NetBox-Verzeichnis nicht gefunden: {netbox_root}")
install_files, manifest = collect_installation_files(netbox_root)
log_info(
" -> Ausgenommen: " + ", ".join(FILES_EXCLUDE_DIRS + FILES_EXCLUDE_NAMES)
+ " (werden von upgrade.sh neu erzeugt bzw. separat gesichert)"
)
log_success(f"{len(install_files)} Installationsdateien gefunden.")
else:
log_info("Schritt 3: Sicherung der Installationsdateien übersprungen.")
# 4. Metadaten
log_info("Schritt 4: Erstelle Metadaten...")
meta = {
"version": BACKUP_FORMAT_VERSION,
"timestamp": stamp,
"source_db": CONFIG["db_name"],
"netbox_path": CONFIG["netbox_path"],
"netbox_root": netbox_root,
"netbox_version": detect_netbox_version(netbox_root) if os.path.isdir(netbox_root) else None,
"contains_db": do_db,
"contains_media": do_media,
"contains_files": do_files,
"media_root": media_path if do_media else None,
"extra_files": extra_files,
"excluded_changelog": exclude_changelog,
"excluded_users": exclude_users,
}
# 5. ZIP erstellen (nur für root lesbar, da Konfiguration und Dump Geheimnisse enthalten)
log_info(f"Schritt 5: Komprimiere Daten nach {zip_file_path} ...")
fd = os.open(zip_file_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
zip_created = True
with os.fdopen(fd, "wb") as raw_handle, zipfile.ZipFile(
raw_handle, "w", zipfile.ZIP_DEFLATED, allowZip64=True
) as zipf:
zipf.writestr("metadata.json", json.dumps(meta, indent=4))
if do_db:
zipf.write(dump_file, "netbox_database.dump")
for full_path, rel_path in media_files:
zipf.write(full_path, f"media/{rel_path}")
for full_path in extra_files:
zipf.write(full_path, "extra_files/" + full_path.lstrip("/"))
if do_files:
zipf.writestr("files_manifest.json", json.dumps(manifest, indent=1))
for full_path, rel_path in install_files:
zipf.write(full_path, f"files/{rel_path}")
except Exception:
if zip_created and os.path.exists(zip_file_path):
os.remove(zip_file_path)
raise
finally:
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
return zip_file_path
# ==========================================
# Kernfunktionen: Restore
# ==========================================
def list_backups():
backup_dir = CONFIG["backup_dir"]
if not os.path.isdir(backup_dir):
return []
candidates = [
os.path.join(backup_dir, name)
for name in os.listdir(backup_dir)
if name.startswith("netbox_") and name.endswith(".zip")
]
return sorted(candidates, key=os.path.getmtime, reverse=True)
def choose_backup_file():
backups = list_backups()
if backups:
log_info(f"Gefundene Backups in {CONFIG['backup_dir']}:")
for index, path in enumerate(backups, 1):
size_mb = os.path.getsize(path) / (1024 * 1024)
modified = datetime.fromtimestamp(os.path.getmtime(path)).strftime("%Y-%m-%d %H:%M")
print(f" {Colors.BOLD}{index}.{Colors.ENDC} {os.path.basename(path)} ({size_mb:.1f} MB, {modified})")
else:
log_info(f"Keine Backups in {CONFIG['backup_dir']} gefunden.")
raw = input("\nNummer oder Pfad zur Backup-ZIP-Datei (leer = Abbruch): ").strip()
if not raw:
return None
if raw.isdigit() and backups and 1 <= int(raw) <= len(backups):
return backups[int(raw) - 1]
if os.path.isfile(raw):
return raw
log_error(f"Die Datei '{raw}' existiert nicht!")
return None
def read_backup_metadata(path):
with zipfile.ZipFile(path, "r") as zipf:
names = set(zipf.namelist())
if "metadata.json" not in names:
raise RuntimeError("Ungültiges Backup: metadata.json fehlt.")
meta = json.loads(zipf.read("metadata.json").decode("utf-8"))
meta.setdefault("contains_db", True)
meta.setdefault("contains_media", True)
meta.setdefault("contains_files", any(name.startswith("files/") for name in names))
return meta
def show_backup_info(path, meta):
def yes_no(value):
return "ja" if value else "nein"
print()
log_info(f"Backup: {path}")
print(f" Erstellt: {meta.get('timestamp', 'unbekannt')}")
print(f" Format-Version: {meta.get('version', 'unbekannt')}")
print(f" NetBox-Version: {meta.get('netbox_version') or 'unbekannt'}")
print(f" Quell-Datenbank: {meta.get('source_db', 'unbekannt')}")
print(f" Datenbank: {yes_no(meta.get('contains_db'))}")
if meta.get("contains_db"):
print(f" ohne Changelog: {yes_no(meta.get('excluded_changelog'))}")
print(f" ohne Benutzer: {yes_no(meta.get('excluded_users'))}")
print(f" Media-Dateien: {yes_no(meta.get('contains_media'))}")
if meta.get("extra_files"):
print(f" + außerhalb MEDIA_ROOT: {len(meta['extra_files'])} Plugin-Dateien")
print(f" Installation: {yes_no(meta.get('contains_files'))}")
def apply_manifest(root, manifest):
"""Stellt Symlinks, Besitzer und Rechte gemäß Backup-Manifest wieder her."""
for entry in manifest:
rel_path = entry.get("path", ".")
path = root if rel_path in ("", ".") else os.path.join(root, *rel_path.split("/"))
if entry.get("type") == "symlink":
if os.path.lexists(path):
continue
os.makedirs(os.path.dirname(path), exist_ok=True)
os.symlink(entry["target"], path)
if hasattr(os, "lchown"):
try:
os.lchown(path, entry["uid"], entry["gid"])
except OSError:
pass
continue
if entry.get("type") == "dir":
os.makedirs(path, exist_ok=True)
if not os.path.lexists(path):
continue
if hasattr(os, "chown"):
try:
os.chown(path, entry["uid"], entry["gid"])
except OSError:
pass
os.chmod(path, entry["mode"])
def restore_installation_files(extract_dir, meta, stamp, keep_current_media):
"""Ersetzt die NetBox-Installation durch die Dateien aus dem Backup.
Die bisherige Installation bleibt erhalten (umbenannt bzw. als altes Symlink-Ziel).
"""
source = os.path.join(extract_dir, "files")
if not os.path.isdir(source):
raise RuntimeError("Ungültiges Backup: Ordner files/ fehlt.")
manifest_file = os.path.join(extract_dir, "files_manifest.json")
manifest = []
if os.path.isfile(manifest_file):
with open(manifest_file, "r", encoding="utf-8") as file_handle:
manifest = json.load(file_handle)
else:
log_warn("Kein files_manifest.json im Backup; Rechte/Besitzer bleiben Standard.")
if not os.path.isfile(os.path.join(source, "netbox", "netbox", "configuration.py")):
raise RuntimeError("Backup enthält keine netbox/netbox/configuration.py.")
if not os.path.isfile(os.path.join(source, "upgrade.sh")):
raise RuntimeError("Backup enthält kein upgrade.sh und ist nicht plausibel.")
netbox_path = os.path.abspath(CONFIG["netbox_path"])
parent = os.path.dirname(netbox_path.rstrip("/")) or "/"
current_root = os.path.realpath(netbox_path) if os.path.lexists(netbox_path) else None
staged = unique_path(os.path.join(parent, f".netbox-restore-{stamp}"))
shutil.move(source, staged)
apply_manifest(staged, manifest)
if keep_current_media and current_root:
current_media = os.path.join(current_root, "netbox", "media")
if os.path.isdir(current_media):
copy_directory_contents_preserve(current_media, os.path.join(staged, "netbox", "media"))
log_info(" -> Aktuelle Media-Dateien in die wiederhergestellte Installation übernommen.")
if os.path.islink(netbox_path):
old_link_target = os.readlink(netbox_path)
version = meta.get("netbox_version") or "unknown"
final_path = unique_path(os.path.join(parent, f"netbox-{version}-restored-{stamp}"))
os.rename(staged, final_path)
temporary_link = unique_path(os.path.join(parent, f".netbox-link-{stamp}"))
os.symlink(final_path, temporary_link)
os.replace(temporary_link, netbox_path)
return {
"mode": "symlink",
"old_link_target": old_link_target,
"old_path": current_root,
"new_path": final_path,
}
old_path = None
if os.path.lexists(netbox_path):
old_path = unique_path(f"{netbox_path.rstrip('/')}_before_restore_{stamp}")
os.rename(netbox_path, old_path)
try:
os.rename(staged, netbox_path)
except Exception:
if old_path:
os.rename(old_path, netbox_path)
raise
return {"mode": "directory", "old_path": old_path, "new_path": netbox_path}
def restore_database_as_superuser(dump_file):
"""Restore über den lokalen postgres-Superuser (Neuinstallation).
Vermeidet Rechteprobleme des NetBox-Benutzers; alle Objekte gehören danach db_user.
"""
user, name = CONFIG["db_user"], CONFIG["db_name"]
log_info("Lösche und erstelle Datenbank neu (als postgres)...")
run_checked(["runuser", "-u", "postgres", "--", "dropdb", "--if-exists", name], "dropdb", cwd="/")
# Explizit UTF-8: Frische Cluster laufen oft mit SQL_ASCII, womit NetBox' ICU-Collation
# "natural_sort" nicht funktioniert und zentrale Tabellen nicht angelegt werden.
run_checked(
["runuser", "-u", "postgres", "--", "createdb", "-O", user, "-E", "UTF8", "-T", "template0",
"--lc-collate=C.UTF-8", "--lc-ctype=C.UTF-8", name],
"createdb",
cwd="/",
)
log_info("Importiere Dump...")
# Dump per stdin übergeben, da das Temp-Verzeichnis für postgres nicht lesbar ist.
with open(dump_file, "rb") as dump_handle:
proc = subprocess.run(
["runuser", "-u", "postgres", "--", "pg_restore", "-d", name,
"--no-owner", "--no-privileges", f"--role={user}"],
stdin=dump_handle,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd="/",
check=False,
)
if proc.returncode != 0:
errors = [line for line in proc.stderr.splitlines() if "error:" in line or "ERROR:" in line]
log_warn(f"pg_restore wurde mit Code {proc.returncode} beendet ({len(errors)} Fehlerzeilen).")
log_warn("Die ersten Fehler (meist die eigentliche Ursache):\n" + "\n".join(errors[:10]))
def verify_restored_database():
"""Bricht ab, wenn zentrale NetBox-Tabellen nach dem Import fehlen."""
env = os.environ.copy()
if CONFIG["db_pass"]:
env["PGPASSWORD"] = CONFIG["db_pass"]
sql = "SELECT count(*) FROM information_schema.tables WHERE table_name IN ('dcim_device','dcim_consoleport','django_migrations')"
proc = run_command(
["psql", "-h", CONFIG["db_host"], "-U", CONFIG["db_user"], "-d", CONFIG["db_name"], "-tAc", sql],
env=env,
capture=True,
)
if proc.returncode != 0 or proc.stdout.strip() != "3":
raise RuntimeError(
"Datenbank-Import unvollständig: zentrale NetBox-Tabellen fehlen. "
"Bitte die pg_restore-Meldungen oben prüfen (häufig: PostgreSQL-Version des Ziels älter als die der Quelle)."
)
log_success("Datenbank-Import geprüft: zentrale Tabellen vorhanden.")
def restore_database(dump_file, as_superuser=False):
if not os.path.exists(dump_file):
raise RuntimeError("Ungültiges Backup: netbox_database.dump fehlt.")
if as_superuser:
restore_database_as_superuser(dump_file)
verify_restored_database()
log_success("Datenbank-Wiederherstellung abgeschlossen.")
return
env = os.environ.copy()
if CONFIG["db_pass"]:
env["PGPASSWORD"] = CONFIG["db_pass"]
log_info("Lösche und erstelle Datenbank neu (Bereinigung)...")
drop_proc = run_command(
["dropdb", "-h", CONFIG["db_host"], "-U", CONFIG["db_user"], "--if-exists", CONFIG["db_name"]],
env=env,
capture=True,
)
if drop_proc.returncode != 0:
raise RuntimeError(f"dropdb fehlgeschlagen: {drop_proc.stderr.strip()}")
create_proc = run_command(
[
"createdb",
"-h",
CONFIG["db_host"],
"-U",
CONFIG["db_user"],
"-O",
CONFIG["db_user"],
CONFIG["db_name"],
],
env=env,
capture=True,
)
if create_proc.returncode != 0:
raise RuntimeError(f"createdb fehlgeschlagen: {create_proc.stderr.strip()}")
log_info("Importiere Dump...")
proc_restore = run_command(
[
"pg_restore",
"-h",
CONFIG["db_host"],
"-U",
CONFIG["db_user"],
"-d",
CONFIG["db_name"],
"--clean",
"--if-exists",
"--no-owner",
dump_file,
],
env=env,
capture=True,
)
if proc_restore.returncode != 0:
log_warn(
f"pg_restore wurde mit Code {proc_restore.returncode} beendet:\n"
f"{proc_restore.stderr.strip()}"
)
verify_restored_database()
log_success("Datenbank-Wiederherstellung abgeschlossen.")
def restore_media(extract_dir, meta):
source_media = os.path.join(extract_dir, "media")
default_media = os.path.join(CONFIG["netbox_path"], "netbox", "media")
old_root = meta.get("netbox_root")
new_root = os.path.realpath(CONFIG["netbox_path"])
def map_path(path):
# Pfade in der alten Installation auf die aktuelle Installation abbilden
# (z. B. /opt/netbox-4.5.0/... -> /opt/netbox-4.6.1/...).
if old_root and is_within(path, old_root):
return os.path.join(new_root, os.path.relpath(path, old_root))
return path
media_path = map_path(meta["media_root"]) if meta.get("media_root") else default_media
if os.path.isdir(source_media):
if os.path.exists(media_path):
shutil.rmtree(media_path)
os.makedirs(os.path.dirname(media_path.rstrip("/")), exist_ok=True)
shutil.copytree(source_media, media_path)
run_command(["chown", "-R", "netbox:netbox", media_path], capture=True)
log_success(f"Media-Dateien wiederhergestellt nach {media_path}.")
else:
log_warn("Backup enthält laut Metadaten Media-Dateien, der Ordner fehlt jedoch.")
extra_source = os.path.join(extract_dir, "extra_files")
extra_files = meta.get("extra_files") or []
restored = 0
for original in extra_files:
source = os.path.join(extra_source, *original.lstrip("/").split("/"))
target = map_path(original)
if not os.path.isfile(source):
log_warn(f" -> Zusatzdatei fehlt im Backup: {target}")
continue
os.makedirs(os.path.dirname(target), exist_ok=True)
shutil.copy2(source, target)
run_command(["chown", "netbox:netbox", target], capture=True)
restored += 1
if extra_files:
log_success(f"{restored} Plugin-/Zusatzdateien außerhalb von MEDIA_ROOT wiederhergestellt.")
def run_netbox_upgrade_script():
upgrade_script = os.path.join(CONFIG["netbox_path"], "upgrade.sh")
if not os.path.exists(upgrade_script):
log_warn(f"Kein upgrade.sh unter {upgrade_script} gefunden.")
return
upgrade_env = os.environ.copy()
if CONFIG.get("python_path"):
upgrade_env["PYTHON"] = CONFIG["python_path"]
upgrade_proc = run_command(
[upgrade_script],
env=upgrade_env,
cwd=CONFIG["netbox_path"],
capture=False,
)
if upgrade_proc.returncode != 0:
raise RuntimeError(f"upgrade.sh fehlgeschlagen (Code {upgrade_proc.returncode}).")
log_success("Upgrade-Skript erfolgreich durchgelaufen.")
RESTORE_COMPONENT_LABELS = {
"files": "Installationsdateien",
"db": "Datenbank",
"media": "Media-Dateien",
}
# Pakete für eine Neuinstallation (Debian/Ubuntu) gemäß NetBox-Installationsanleitung.
GREENFIELD_APT_PACKAGES = (
"postgresql",
"redis-server",
"python3",
"python3-pip",
"python3-venv",
"python3-dev",
"build-essential",
"libxml2-dev",
"libxslt1-dev",
"libffi-dev",
"libpq-dev",
"libssl-dev",
"zlib1g-dev",
"git",
)
def sql_literal(value):
return "'" + value.replace("'", "''") + "'"
def sql_identifier(value):
return '"' + value.replace('"', '""') + '"'
def run_checked(command, description, **kwargs):
proc = run_command(command, capture=True, **kwargs)
if proc.returncode != 0:
raise RuntimeError(f"{description} fehlgeschlagen: {(proc.stderr or proc.stdout).strip()}")
return proc
def greenfield_install_packages(with_nginx):
if not shutil.which("apt-get"):
raise RuntimeError("Neuinstallation wird nur auf Debian/Ubuntu (apt-get) unterstützt.")
packages = list(GREENFIELD_APT_PACKAGES)
if with_nginx:
packages += ["nginx", "openssl"]
env = os.environ.copy()
env["DEBIAN_FRONTEND"] = "noninteractive"
log_info(" -> apt-get update ...")
run_checked(["apt-get", "update"], "apt-get update", env=env)
log_info(" -> Installiere: " + " ".join(packages))
proc = run_command(["apt-get", "install", "-y", *packages], env=env)
if proc.returncode != 0:
raise RuntimeError(f"apt-get install fehlgeschlagen (Code {proc.returncode}).")
for service in ("postgresql", "redis-server"):
run_command(["systemctl", "enable", "--now", service], capture=True)
log_success("Systempakete installiert, PostgreSQL und Redis laufen.")
def greenfield_setup_database():
"""Legt PostgreSQL-Rolle und Datenbank an (Rolle darf Datenbanken erstellen)."""
user, name, password = CONFIG["db_user"], CONFIG["db_name"], CONFIG["db_pass"]
def psql(sql):
return run_checked(
["runuser", "-u", "postgres", "--", "psql", "-v", "ON_ERROR_STOP=1", "-tAc", sql],
"psql",
cwd="/",
)
exists = psql(f"SELECT 1 FROM pg_roles WHERE rolname = {sql_literal(user)}").stdout.strip() == "1"
verb = "ALTER" if exists else "CREATE"
psql(f"{verb} ROLE {sql_identifier(user)} WITH LOGIN CREATEDB PASSWORD {sql_literal(password)}")
log_success(f"PostgreSQL-Rolle '{user}' {'aktualisiert' if exists else 'angelegt'}.")
db_exists = psql(f"SELECT 1 FROM pg_database WHERE datname = {sql_literal(name)}").stdout.strip() == "1"
if not db_exists:
psql(f"CREATE DATABASE {sql_identifier(name)} OWNER {sql_identifier(user)}")
log_success(f"Datenbank '{name}' angelegt.")
def greenfield_create_system_user():
if run_command(["id", "netbox"], capture=True).returncode == 0:
log_info(" -> Systembenutzer 'netbox' existiert bereits.")
return
run_checked(
["adduser", "--system", "--group", "--no-create-home", "netbox"]
if shutil.which("adduser")
else ["useradd", "--system", "--user-group", "--no-create-home", "netbox"],
"Anlegen des Systembenutzers netbox",
)
log_success("Systembenutzer 'netbox' angelegt.")
def greenfield_install_services():
"""Richtet gunicorn.py und die systemd-Units aus contrib/ ein."""
root = CONFIG["netbox_path"]
contrib = os.path.join(root, "contrib")
gunicorn_target = os.path.join(root, "gunicorn.py")
if not os.path.isfile(gunicorn_target) and os.path.isfile(os.path.join(contrib, "gunicorn.py")):
shutil.copy2(os.path.join(contrib, "gunicorn.py"), gunicorn_target)
units = [name for name in os.listdir(contrib) if name.endswith((".service", ".timer"))] if os.path.isdir(contrib) else []
if not units:
raise RuntimeError(f"Keine systemd-Units unter {contrib} gefunden.")
for name in units:
target = os.path.join("/etc/systemd/system", name)
if not os.path.exists(target):
shutil.copy2(os.path.join(contrib, name), target)
run_checked(["systemctl", "daemon-reload"], "systemctl daemon-reload")
for service in NETBOX_SERVICES:
run_checked(["systemctl", "enable", service], f"systemctl enable {service}")
if "netbox-housekeeping.timer" in units:
run_command(["systemctl", "enable", "--now", "netbox-housekeeping.timer"], capture=True)
log_success("systemd-Dienste eingerichtet und aktiviert.")
def greenfield_setup_nginx():
contrib_conf = os.path.join(CONFIG["netbox_path"], "contrib", "nginx.conf")
if not os.path.isfile(contrib_conf):
log_warn("contrib/nginx.conf nicht gefunden; nginx wird nicht konfiguriert.")
return
server_name = input(" Servername für nginx/Zertifikat (z. B. netbox.example.com): ").strip() or "_"
cert, key = "/etc/ssl/certs/netbox.crt", "/etc/ssl/private/netbox.key"
if not (os.path.exists(cert) and os.path.exists(key)):
cn = server_name if server_name != "_" else "netbox"
run_checked(
["openssl", "req", "-x509", "-nodes", "-days", "825", "-newkey", "rsa:2048",
"-keyout", key, "-out", cert, "-subj", f"/CN={cn}"],
"Erzeugen des selbstsignierten Zertifikats",
)
os.chmod(key, 0o600)
log_info(" -> Selbstsigniertes Zertifikat erzeugt (später durch ein echtes ersetzen).")
with open(contrib_conf, "r", encoding="utf-8") as handle:
content = handle.read().replace("netbox.example.com", server_name)
with open("/etc/nginx/sites-available/netbox", "w", encoding="utf-8") as handle:
handle.write(content)
default_site = "/etc/nginx/sites-enabled/default"
if os.path.islink(default_site):
os.remove(default_site)
enabled = "/etc/nginx/sites-enabled/netbox"
if not os.path.lexists(enabled):
os.symlink("/etc/nginx/sites-available/netbox", enabled)
run_checked(["nginx", "-t"], "nginx-Konfigurationstest")
run_checked(["systemctl", "restart", "nginx"], "nginx-Neustart")
log_success("nginx eingerichtet.")
def execute_greenfield_restore():
"""Installiert NetBox auf einem frischen System und spielt danach das komplette Backup ein."""
print_header("NEUINSTALLATION AUS BACKUP (GRÜNE WIESE)")
log_info(
"Richtet auf einem frischen Debian/Ubuntu-System alles Nötige ein (Pakete, PostgreSQL, Redis, "
"Benutzer 'netbox', systemd-Dienste, optional nginx) und führt anschließend einen Komplett-Restore aus."
)
log_info(
f"Datenbank: {CONFIG['db_name']} / Benutzer: {CONFIG['db_user']} @ {CONFIG['db_host']} "
f"– Installationspfad: {CONFIG['netbox_path']}"
)
log_warn("Die Werte müssen zur configuration.py im Backup passen (ggf. vorher in den Einstellungen anpassen).")
if CONFIG["db_host"] not in ("localhost", "127.0.0.1", "::1"):
log_error("Die Neuinstallation richtet PostgreSQL lokal ein; db_host muss localhost sein.")
pause()
return
if not CONFIG["db_pass"]:
password = input("\nPasswort für den PostgreSQL-Benutzer (wie in configuration.py): ").strip()
if not password:
log_error("Ohne Datenbank-Passwort ist keine Neuinstallation möglich.")
pause()
return
CONFIG["db_pass"] = password
with_nginx = input("\nnginx mit selbstsigniertem Zertifikat einrichten? (j/N): ").strip().lower() == "j"
execute_restore(None, greenfield={"nginx": with_nginx})
def execute_restore(components=None, greenfield=None):
"""Stellt die gewählten Komponenten wieder her (None = alles, was im Backup enthalten ist).
greenfield: dict mit Optionen für eine Neuinstallation (siehe execute_greenfield_restore).
"""
print_header("RESTORE PROZESS" if not greenfield else "NEUINSTALLATION AUS BACKUP")
if os.name != "posix" or os.geteuid() != 0:
log_error("Der Restore muss unter Linux als root bzw. mit sudo ausgeführt werden.")
pause()
return
restore_file = choose_backup_file()
if not restore_file:
pause()
return
try:
meta = read_backup_metadata(restore_file)
except Exception as exc:
log_error(f"Backup kann nicht gelesen werden: {exc}")
pause()
return
available = {key: bool(meta.get(f"contains_{key}")) for key in RESTORE_COMPONENT_LABELS}
requested = set(available) if components is None else set(components)
selected = [key for key in RESTORE_COMPONENT_LABELS if key in requested and available[key]]
for key in requested:
if not available[key] and components is not None:
log_warn(f"{RESTORE_COMPONENT_LABELS[key]} sind in diesem Backup nicht enthalten.")
if not selected:
log_error("Im Backup ist nichts Passendes zum Wiederherstellen enthalten.")
pause()
return
if greenfield and not (available["files"] and available["db"]):
log_error("Für eine Neuinstallation muss das Backup Installationsdateien und Datenbank enthalten.")
pause()
return
show_backup_info(restore_file, meta)
if greenfield and os.path.lexists(CONFIG["netbox_path"]):
log_warn(
f"Unter {CONFIG['netbox_path']} existiert bereits etwas; es wird beim Restore beiseitegelegt, "
"nicht gelöscht."
)
backup_version = meta.get("netbox_version")
installed_version = (
detect_netbox_version(os.path.realpath(CONFIG["netbox_path"]))
if os.path.isdir(CONFIG["netbox_path"])
else None
)
if "db" in selected and "files" not in selected and backup_version and installed_version:
if version_tuple(backup_version) > version_tuple(installed_version):
log_warn(
f"Die Datenbank stammt von NetBox v{backup_version}, installiert ist v{installed_version}. "
"Ältere NetBox-Versionen können neuere Datenbankschemata nicht verwenden. "
"Ggf. zusätzlich die Installationsdateien wiederherstellen."
)
print()
log_warn("ACHTUNG: Dieser Vorgang überschreibt bestehende Daten auf dieser Instanz!")
log_info("Wird wiederhergestellt: " + ", ".join(RESTORE_COMPONENT_LABELS[key] for key in selected))
if input("Bist du sicher, dass du fortfahren möchtest? (j/N): ").strip().lower() != "j":
log_info("Abbruch durch Benutzer.")
pause()
return
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
os.makedirs(CONFIG["backup_dir"], exist_ok=True)
tmp_extract_dir = tempfile.mkdtemp(prefix=f"nb_restore_{stamp}_", dir=CONFIG["backup_dir"])
services_stopped = False
file_switch = None
try:
log_info(f"\nSchritt 1: Entpacke {restore_file} ...")
with zipfile.ZipFile(restore_file, "r") as zipf:
safe_extract_zip(zipf, tmp_extract_dir)
if greenfield:
log_info("Schritt 1a: Installiere Systempakete...")
greenfield_install_packages(greenfield.get("nginx"))
log_info("Schritt 1b: Richte PostgreSQL-Rolle und Datenbank ein...")
greenfield_setup_database()
log_info("Schritt 1c: Prüfe Systembenutzer 'netbox'...")
greenfield_create_system_user()
log_info("Schritt 2: Stoppe NetBox-Dienste...")
stop_services()
services_stopped = True
if "files" in selected:
log_info("Schritt 3a: Stelle Installationsdateien wieder her...")
file_switch = restore_installation_files(
tmp_extract_dir,
meta,
stamp,
keep_current_media="media" not in selected,
)
log_success(f"Installation wiederhergestellt unter: {file_switch['new_path']}")
if file_switch.get("old_path"):
log_info(f" -> Bisherige Installation verbleibt unter: {file_switch['old_path']}")
if greenfield:
log_info("Schritt 3a+: Richte systemd-Dienste ein...")
greenfield_install_services()
if "db" in selected:
log_info("Schritt 3b: Stelle PostgreSQL-Datenbank wieder her...")
restore_database(
os.path.join(tmp_extract_dir, "netbox_database.dump"),
as_superuser=bool(greenfield),
)
if "media" in selected:
log_info("Schritt 3c: Stelle Media-Dateien wieder her...")
restore_media(tmp_extract_dir, meta)
if "db" in selected or "files" in selected:
log_info("Schritt 4: Führe NetBox upgrade.sh aus (venv, Migrationen, Static Files)...")
run_netbox_upgrade_script()
else:
log_info("Schritt 4: upgrade.sh nicht erforderlich (nur Media wiederhergestellt).")
log_info("Schritt 5: Starte NetBox-Dienste neu...")
restart_services(strict=True)
services_stopped = False
if greenfield and greenfield.get("nginx"):
log_info("Schritt 6: Richte nginx ein...")
greenfield_setup_nginx()
print("\n" + "=" * 60)
log_success("RESTORE ERFOLGREICH ABGESCHLOSSEN!")
print("=" * 60)
except Exception as exc:
log_error(f"Fehler beim Restore: {exc}")
if file_switch and file_switch.get("old_path"):
log_info(f"Vorherige Installation liegt weiterhin unter: {file_switch['old_path']}")
if services_stopped:
restart_services(strict=False)
finally:
if os.path.exists(tmp_extract_dir):
shutil.rmtree(tmp_extract_dir)
pause()
def show_backup_details():
print_header("BACKUP-INHALT ANZEIGEN")
restore_file = choose_backup_file()
if restore_file:
try:
show_backup_info(restore_file, read_backup_metadata(restore_file))
except Exception as exc:
log_error(f"Backup kann nicht gelesen werden: {exc}")
pause()
def restore_menu():
while True:
print_header("RESTORE-MENÜ")
print(f" {Colors.BOLD}1.{Colors.ENDC} Komplett-Restore (alles, was im Backup enthalten ist)")
print(f" {Colors.BOLD}2.{Colors.ENDC} Nur Datenbank wiederherstellen")
print(f" {Colors.BOLD}3.{Colors.ENDC} Nur Media-Dateien wiederherstellen")
print(f" {Colors.BOLD}4.{Colors.ENDC} Nur Installationsdateien wiederherstellen")
print(f" {Colors.BOLD}5.{Colors.ENDC} Neuinstallation auf grüner Wiese (System einrichten + Komplett-Restore)")
print(f" {Colors.BOLD}6.{Colors.ENDC} Backup-Inhalt anzeigen")
print(f" {Colors.BOLD}7.{Colors.ENDC} Zurück zum Hauptmenü\n")
choice = input(Colors.BOLD + "Wähle eine Aktion (1-7): " + Colors.ENDC).strip()
actions = {
"1": lambda: execute_restore(None),
"2": lambda: execute_restore({"db"}),
"3": lambda: execute_restore({"media"}),
"4": lambda: execute_restore({"files"}),
"5": execute_greenfield_restore,
"6": show_backup_details,
}
if choice == "7":
return
if choice in actions:
actions[choice]()
return
log_error("Ungültige Eingabe.")
time.sleep(1)
# ==========================================
# Kernfunktionen: NetBox-Upgrade
# ==========================================
def normalize_version(raw_version):
version = raw_version.strip()
if version.lower().startswith("v"):
version = version[1:]
if not re.fullmatch(r"\d+\.\d+\.\d+", version):
raise ValueError("Bitte eine stabile Version im Format X.Y.Z eingeben, z. B. 4.6.5.")
return version
def version_tuple(version):
return tuple(int(part) for part in version.split("."))
def detect_netbox_version(netbox_root):
"""Versucht die installierte NetBox-Version ohne Django-Start zu erkennen."""
basename = os.path.basename(os.path.realpath(netbox_root))
match = re.search(r"netbox-v?(\d+\.\d+\.\d+)$", basename)
if match:
return match.group(1)
git_dir = os.path.join(netbox_root, ".git")
if os.path.isdir(git_dir):
proc = run_command(
["git", "-C", netbox_root, "describe", "--tags", "--exact-match"],
capture=True,
)
if proc.returncode == 0:
value = proc.stdout.strip().lstrip("v")
if re.fullmatch(r"\d+\.\d+\.\d+", value):
return value
python_bin = os.path.join(netbox_root, "venv", "bin", "python")
package_root = os.path.join(netbox_root, "netbox")
if os.path.isfile(python_bin) and os.path.isdir(package_root):
code = (
"import sys; "
f"sys.path.insert(0, {package_root!r}); "
"import netbox; "
"print(getattr(netbox, '__version__', ''))"
)
proc = run_command([python_bin, "-c", code], capture=True)
value = proc.stdout.strip().lstrip("v") if proc.returncode == 0 else ""
if re.fullmatch(r"\d+\.\d+\.\d+", value):
return value
candidate_files = (
os.path.join(netbox_root, "netbox", "netbox", "version.py"),
os.path.join(netbox_root, "netbox", "netbox", "__init__.py"),
)
pattern = re.compile(r"(?:__version__|VERSION)\s*=\s*['\"]v?(\d+\.\d+\.\d+)['\"]")
for candidate in candidate_files:
if not os.path.isfile(candidate):
continue
try:
with open(candidate, "r", encoding="utf-8") as file_handle:
match = pattern.search(file_handle.read())
if match:
return match.group(1)
except OSError:
pass
return None
def download_release(version, destination):
url = f"https://github.com/netbox-community/netbox/archive/refs/tags/v{version}.tar.gz"
request = urllib.request.Request(
url,
headers={"User-Agent": "netbox-backup-restore-upgrade-tool/1.2"},
)
try:
with urllib.request.urlopen(request, timeout=90) as response, open(destination, "wb") as output:
total = int(response.headers.get("Content-Length", "0") or 0)
downloaded = 0
while True:
chunk = response.read(1024 * 1024)
if not chunk:
break
output.write(chunk)
downloaded += len(chunk)
if total:
percent = downloaded * 100 / total
print(f"\r Download: {percent:5.1f}%", end="", flush=True)
if total:
print()
except urllib.error.HTTPError as exc:
if exc.code == 404:
raise RuntimeError(f"NetBox-Release v{version} wurde auf GitHub nicht gefunden.") from exc
raise RuntimeError(f"HTTP-Fehler beim Download: {exc}") from exc
except urllib.error.URLError as exc:
raise RuntimeError(f"Download fehlgeschlagen: {exc.reason}") from exc
def find_extracted_release(staging_dir, version):
expected = os.path.join(staging_dir, f"netbox-{version}")
if os.path.isdir(expected):
return expected
directories = [
os.path.join(staging_dir, name)
for name in os.listdir(staging_dir)
if os.path.isdir(os.path.join(staging_dir, name))
]
if len(directories) == 1:
return directories[0]
raise RuntimeError("Das entpackte NetBox-Verzeichnis konnte nicht eindeutig ermittelt werden.")
def copy_file_preserve(source, destination):
os.makedirs(os.path.dirname(destination), exist_ok=True)
proc = run_command(["cp", "-a", "--", source, destination], capture=True)
if proc.returncode != 0:
raise RuntimeError(f"Kopieren fehlgeschlagen ({source}): {proc.stderr.strip()}")
def copy_directory_contents_preserve(source, destination):
os.makedirs(destination, exist_ok=True)
proc = run_command(["cp", "-a", "--", os.path.join(source, "."), destination], capture=True)
if proc.returncode != 0:
raise RuntimeError(f"Kopieren fehlgeschlagen ({source}): {proc.stderr.strip()}")
def copy_upgrade_data(current_root, new_root):
copied = []
required_files = (
(
os.path.join(current_root, "netbox", "netbox", "configuration.py"),
os.path.join(new_root, "netbox", "netbox", "configuration.py"),
True,
),
(
os.path.join(current_root, "netbox", "netbox", "ldap_config.py"),
os.path.join(new_root, "netbox", "netbox", "ldap_config.py"),
False,
),
(
os.path.join(current_root, "local_requirements.txt"),
os.path.join(new_root, "local_requirements.txt"),
False,
),
(
os.path.join(current_root, "gunicorn.py"),
os.path.join(new_root, "gunicorn.py"),
False,
),
)
for source, destination, mandatory in required_files:
if os.path.isfile(source):
copy_file_preserve(source, destination)
copied.append(os.path.relpath(source, current_root))
elif mandatory:
raise RuntimeError(f"Pflichtdatei fehlt: {source}")
else:
log_info(f" -> Optional nicht vorhanden: {source}")
directory_pairs = (
(
os.path.join(current_root, "netbox", "media"),
os.path.join(new_root, "netbox", "media"),
),
(
os.path.join(current_root, "netbox", "scripts"),
os.path.join(new_root, "netbox", "scripts"),
),
(
os.path.join(current_root, "netbox", "reports"),
os.path.join(new_root, "netbox", "reports"),
),
)
for source, destination in directory_pairs:
if os.path.isdir(source):
copy_directory_contents_preserve(source, destination)
copied.append(os.path.relpath(source, current_root) + "/")
else:
log_info(f" -> Optional nicht vorhanden: {source}")
return copied
def requirement_key(requirement):
value = requirement.strip()
if not value or value.startswith("#") or value.startswith("-"):
return None
egg_match = re.search(r"#egg=([A-Za-z0-9_.-]+)", value, flags=re.IGNORECASE)
if egg_match:
return egg_match.group(1).lower().replace("_", "-")
value = re.split(r"\s+#", value, maxsplit=1)[0].strip()
pep508_match = re.match(r"([A-Za-z0-9_.-]+)\s*@", value)
if pep508_match:
return pep508_match.group(1).lower().replace("_", "-")
package_match = re.match(r"([A-Za-z0-9_.-]+)", value)
if package_match:
return package_match.group(1).lower().replace("_", "-")
return value.lower()
def merge_local_requirements(new_root, include_default_plugins, include_ldap):
requirements_file = os.path.join(new_root, "local_requirements.txt")
existing_lines = []
if os.path.exists(requirements_file):
with open(requirements_file, "r", encoding="utf-8") as file_handle:
existing_lines = file_handle.read().splitlines()
existing_keys = {
key for key in (requirement_key(line) for line in existing_lines) if key is not None
}
desired = []
if include_default_plugins:
desired.extend(DEFAULT_PLUGIN_REQUIREMENTS)
if include_ldap:
desired.append(LDAP_REQUIREMENT)
added = []
for requirement in desired:
key = requirement_key(requirement)
if key in existing_keys:
continue
existing_lines.append(requirement)
existing_keys.add(key)
added.append(requirement)
if desired or os.path.exists(requirements_file):
with open(requirements_file, "w", encoding="utf-8") as file_handle:
content = "\n".join(existing_lines).rstrip()
if content:
file_handle.write(content + "\n")
return added
def has_csrf_setting(configuration_file):
try:
with open(configuration_file, "r", encoding="utf-8") as file_handle:
content = file_handle.read()
except OSError:
return False
return bool(re.search(r"^\s*CSRF_TRUSTED_ORIGINS\s*=", content, flags=re.MULTILINE))
def parse_csrf_origins(raw_value):
origins = []
for value in raw_value.split(","):
origin = value.strip().rstrip("/")
if not origin:
continue
parsed = urllib.parse.urlparse(origin)
if parsed.scheme not in ("http", "https") or not parsed.netloc:
raise ValueError(f"Ungültiger CSRF-Origin: {origin}")
if parsed.path not in ("", "/") or parsed.params or parsed.query or parsed.fragment:
raise ValueError(f"CSRF-Origin darf keinen Pfad/Query enthalten: {origin}")
if origin not in origins:
origins.append(origin)
return origins
def append_csrf_setting(configuration_file, origins):
with open(configuration_file, "a", encoding="utf-8") as file_handle:
file_handle.write("\n# Automatisch durch das NetBox-Upgrade-Tool gesetzt\n")
file_handle.write("CSRF_TRUSTED_ORIGINS = [\n")
for origin in origins:
file_handle.write(f" {origin!r},\n")
file_handle.write("]\n")
def stop_services():
log_info("Stoppe NetBox-Dienste für die Umschaltung...")
for service in NETBOX_SERVICES:
proc = run_command(["systemctl", "stop", service], capture=True)
if proc.returncode != 0:
log_warn(f"{service} konnte nicht sauber gestoppt werden: {proc.stderr.strip()}")
status = run_command(["systemctl", "is-active", service], capture=True)
if status.stdout.strip() == "active":
raise RuntimeError(f"Dienst {service} läuft trotz Stop-Befehl weiter.")
def restart_services(strict=False):
failures = []
for service in NETBOX_SERVICES:
proc = run_command(["systemctl", "restart", service], capture=True)
if proc.returncode != 0:
failures.append(f"{service}: {proc.stderr.strip()}")
continue
status = run_command(["systemctl", "is-active", service], capture=True)
if status.stdout.strip() != "active":
failures.append(f"{service}: Status ist '{status.stdout.strip() or 'unbekannt'}'")
else:
log_success(f"Dienst {service} ist aktiv.")
if failures:
message = " | ".join(failures)
if strict:
raise RuntimeError(f"Dienst-Neustart fehlgeschlagen: {message}")
log_warn(f"Dienst-Neustart mit Problemen: {message}")
def switch_installation(netbox_path, extracted_root, version, stamp):
"""Schaltet entweder einen Symlink oder ein echtes /opt/netbox-Verzeichnis um."""
parent = os.path.dirname(netbox_path.rstrip("/")) or "/"
if os.path.islink(netbox_path):
old_link_target = os.readlink(netbox_path)
version_path = os.path.join(parent, f"netbox-{version}")
if os.path.lexists(version_path):
raise RuntimeError(
f"Zielverzeichnis existiert bereits: {version_path}. "
"Bitte zuerst prüfen oder umbenennen."
)
os.rename(extracted_root, version_path)
temporary_link = unique_path(os.path.join(parent, f".netbox-link-{stamp}"))
os.symlink(version_path, temporary_link)
os.replace(temporary_link, netbox_path)
return {
"mode": "symlink",
"netbox_path": netbox_path,
"old_link_target": old_link_target,
"new_path": version_path,
"old_path": os.path.realpath(
old_link_target
if os.path.isabs(old_link_target)
else os.path.join(parent, old_link_target)
),
}
old_path = unique_path(os.path.join(parent, f"netbox_old_{stamp}"))
os.rename(netbox_path, old_path)
try:
os.rename(extracted_root, netbox_path)
except Exception:
os.rename(old_path, netbox_path)
raise
return {
"mode": "directory",
"netbox_path": netbox_path,
"old_path": old_path,
"new_path": netbox_path,
}
def rollback_filesystem_switch(switch_state, stamp):
"""Nur vor Start von upgrade.sh sicher; danach könnten DB-Migrationen erfolgt sein."""
if switch_state["mode"] == "symlink":
parent = os.path.dirname(switch_state["netbox_path"].rstrip("/")) or "/"
temporary_link = unique_path(os.path.join(parent, f".netbox-rollback-{stamp}"))
os.symlink(switch_state["old_link_target"], temporary_link)
os.replace(temporary_link, switch_state["netbox_path"])
return
failed_path = unique_path(f"{switch_state['netbox_path']}_failed_{stamp}")
os.rename(switch_state["netbox_path"], failed_path)
os.rename(switch_state["old_path"], switch_state["netbox_path"])
switch_state["failed_path"] = failed_path
def execute_upgrade():
print_header("NETBOX UPGRADE")
if os.name != "posix" or os.geteuid() != 0:
log_error("Das Upgrade muss unter Linux als root bzw. mit sudo ausgeführt werden.")
pause()
return
netbox_path = os.path.abspath(CONFIG["netbox_path"])
if not os.path.lexists(netbox_path):
log_error(f"NetBox-Pfad existiert nicht: {netbox_path}")
pause()
return
current_root = os.path.realpath(netbox_path)
current_config = os.path.join(current_root, "netbox", "netbox", "configuration.py")
if not os.path.isfile(current_config):
log_error(f"Keine gültige NetBox-Installation erkannt; configuration.py fehlt: {current_config}")
pause()
return
current_version = detect_netbox_version(current_root)
if current_version:
log_info(f"Erkannte installierte Version: v{current_version}")
else:
log_warn("Die installierte NetBox-Version konnte nicht sicher erkannt werden.")
try:
target_version = normalize_version(input("Zielversion (X.Y.Z, optional mit v): "))
except ValueError as exc:
log_error(str(exc))
pause()
return
if current_version:
current_tuple = version_tuple(current_version)
target_tuple = version_tuple(target_version)
if target_tuple <= current_tuple:
log_error(
f"Die Zielversion v{target_version} ist nicht neuer als v{current_version}. "
"Downgrades werden absichtlich nicht automatisiert."
)
pause()
return
if target_tuple[0] > current_tuple[0]:
log_warn(
"Major-Upgrade erkannt. NetBox erlaubt einen Major-Sprung nur von der "
"jeweils letzten Minor-Version des bisherigen Major-Releases."
)
print()
log_info(f"Release Notes: https://github.com/netbox-community/netbox/releases/tag/v{target_version}")
if input("Release Notes geprüft? (j/N): ").strip().lower() != "j":
log_info("Upgrade abgebrochen. Bitte zuerst die Release Notes prüfen.")
pause()
return
log_info(
"Vor dem Upgrade wird automatisch ein vollständiges Backup "
"(Datenbank, Media und Installationsdateien) erstellt."
)
skip_backup = False
if input("Automatisches Backup überspringen? (j/N): ").strip().lower() == "j":
log_warn("Ohne Backup ist bei fehlgeschlagenen Migrationen keine Wiederherstellung möglich!")
if input("Wirklich OHNE Backup fortfahren? Zur Bestätigung 'OHNE BACKUP' eingeben: ").strip() != "OHNE BACKUP":
log_info("Backup wird erstellt.")
else:
skip_backup = True
include_plugins = (
input("Genannte Standard-Plugins in local_requirements.txt ergänzen? (J/n): ")
.strip()
.lower()
!= "n"
)
ldap_present = os.path.isfile(
os.path.join(current_root, "netbox", "netbox", "ldap_config.py")
)
if ldap_present:
log_info("LDAP-Konfiguration erkannt; django-auth-ldap wird sichergestellt.")
csrf_present = has_csrf_setting(current_config)
log_info(
"CSRF_TRUSTED_ORIGINS ist in configuration.py vorhanden."
if csrf_present
else "CSRF_TRUSTED_ORIGINS wurde nicht als direkte Zuweisung erkannt."
)
csrf_raw = input(
"Neue CSRF_TRUSTED_ORIGINS kommagetrennt eingeben "
"(leer = vorhandene Konfiguration übernehmen): "
).strip()
try:
csrf_origins = parse_csrf_origins(csrf_raw) if csrf_raw else []
except ValueError as exc:
log_error(str(exc))
pause()
return
if not csrf_present and not csrf_origins:
log_warn(
"Kein CSRF_TRUSTED_ORIGINS erkannt. Die Einstellung kann allerdings auch "
"dynamisch/importiert gesetzt sein."
)
if input("Trotzdem fortfahren? (j/N): ").strip().lower() != "j":
log_info("Upgrade abgebrochen.")
pause()
return
print()
log_warn(
"Plugin-Kompatibilität wird erst während upgrade.sh/Pip geprüft. "
"Nicht kompatible Plugins können das Upgrade stoppen."
)
if input(f"Upgrade auf NetBox v{target_version} jetzt starten? (j/N): ").strip().lower() != "j":
log_info("Upgrade abgebrochen.")
pause()
return
install_parent = os.path.dirname(netbox_path.rstrip("/")) or "/"
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
staging_dir = None
archive_path = None
switch_state = None
services_stopped = False
upgrade_started = False
backup_file = None
try:
if not shutil.which("cp"):
raise RuntimeError("Der Befehl 'cp' wurde nicht gefunden.")
if not shutil.which("systemctl"):
raise RuntimeError("Der Befehl 'systemctl' wurde nicht gefunden.")
os.makedirs(CONFIG["backup_dir"], exist_ok=True)
if skip_backup:
log_warn("Schritt 0: Backup auf Wunsch übersprungen.")
else:
log_info("Schritt 0: Erstelle Backup vor dem Upgrade...")
if not shutil.which("pg_dump"):
raise RuntimeError("Der Befehl 'pg_dump' wurde nicht gefunden; Backup nicht möglich.")
backup_file = create_backup(name_prefix=f"netbox_pre_upgrade_v{target_version}")
log_success(f"Backup erstellt: {backup_file}")
fd, archive_path = tempfile.mkstemp(
prefix=f"netbox-v{target_version}-",
suffix=".tar.gz",
dir=CONFIG["backup_dir"],
)
os.close(fd)
staging_dir = tempfile.mkdtemp(prefix=".netbox-upgrade-", dir=install_parent)
log_info(f"Schritt 1: Lade NetBox v{target_version} herunter...")
download_release(target_version, archive_path)
log_success("Release-Archiv heruntergeladen.")
log_info("Schritt 2: Entpacke und prüfe Release-Archiv...")
with tarfile.open(archive_path, "r:gz") as tarf:
safe_extract_tar(tarf, staging_dir)
extracted_root = find_extracted_release(staging_dir, target_version)
required_upgrade_script = os.path.join(extracted_root, "upgrade.sh")
if not os.path.isfile(required_upgrade_script):
raise RuntimeError("Das Release enthält kein upgrade.sh und ist nicht plausibel.")
log_success("Release-Archiv erfolgreich geprüft.")
log_info("Schritt 3: Übernehme Konfiguration, Media, Skripte und Reports...")
copied = copy_upgrade_data(current_root, extracted_root)
for item in copied:
log_info(f" -> übernommen: {item}")
added_requirements = merge_local_requirements(
extracted_root,
include_default_plugins=include_plugins,
include_ldap=ldap_present,
)
if added_requirements:
for requirement in added_requirements:
log_info(f" -> Requirement ergänzt: {requirement}")
else:
log_info(" -> Keine neuen Requirements erforderlich.")
new_configuration = os.path.join(
extracted_root, "netbox", "netbox", "configuration.py"
)
if csrf_origins:
append_csrf_setting(new_configuration, csrf_origins)
log_success("CSRF_TRUSTED_ORIGINS wurde in der neuen Konfiguration gesetzt.")
elif has_csrf_setting(new_configuration):
log_success("Vorhandenes CSRF_TRUSTED_ORIGINS wurde übernommen.")
else:
log_warn("CSRF_TRUSTED_ORIGINS bleibt unverändert bzw. dynamisch konfiguriert.")
log_info("Schritt 4: Stoppe Dienste und schalte auf die neue Version um...")
stop_services()
services_stopped = True
switch_state = switch_installation(
netbox_path,
extracted_root,
target_version,
stamp,
)
log_success("NetBox-Verzeichnis wurde umgeschaltet.")
log_info("Schritt 5: Führe /opt/netbox/upgrade.sh aus...")
upgrade_script = os.path.join(netbox_path, "upgrade.sh")
upgrade_env = os.environ.copy()
if CONFIG.get("python_path"):
if not os.path.isfile(CONFIG["python_path"]):
raise RuntimeError(
f"Konfigurierter Python-Pfad existiert nicht: {CONFIG['python_path']}"
)
upgrade_env["PYTHON"] = CONFIG["python_path"]
log_info(f"Verwende PYTHON={CONFIG['python_path']}")
upgrade_started = True
upgrade_proc = run_command(
[upgrade_script],
env=upgrade_env,
cwd=netbox_path,
capture=False,
)
if upgrade_proc.returncode != 0:
raise RuntimeError(
f"NetBox upgrade.sh wurde mit Code {upgrade_proc.returncode} beendet."
)
log_success("upgrade.sh wurde erfolgreich abgeschlossen.")
log_info("Schritt 6: Starte NetBox-Dienste neu und prüfe den Status...")
restart_services(strict=True)
services_stopped = False
print("\n" + "=" * 60)
log_success(f"UPGRADE AUF NETBOX v{target_version} ERFOLGREICH!")
if switch_state["mode"] == "directory":
log_info(f"Alte Installation verbleibt unter: {switch_state['old_path']}")
else:
log_info(f"Vorheriges Release verbleibt unter: {switch_state['old_path']}")
log_info(f"Aktives Release: {switch_state['new_path']}")
print("=" * 60)
except Exception as exc:
log_error(f"Upgrade fehlgeschlagen: {exc}")
if switch_state and not upgrade_started:
log_warn("Fehler trat vor Start von upgrade.sh auf; Dateisystem-Umschaltung wird zurückgenommen.")
try:
rollback_filesystem_switch(switch_state, stamp)
log_success("Vorherige Installation wurde wieder aktiviert.")
if services_stopped:
restart_services(strict=False)
services_stopped = False
except Exception as rollback_exc:
log_error(f"Automatischer Dateisystem-Rollback fehlgeschlagen: {rollback_exc}")
elif switch_state and upgrade_started:
log_error(
"Kein automatischer Rollback nach Start von upgrade.sh: "
"Datenbank-Migrationen könnten bereits angewendet worden sein."
)
log_info(f"Vorherige Installation liegt weiterhin unter: {switch_state['old_path']}")
if backup_file:
log_info(
"Für einen vollständigen Rollback im Restore-Menü 'Komplett-Restore' "
f"mit diesem Backup ausführen: {backup_file}"
)
else:
log_info("Für einen vollständigen Rollback Datenbank/Media aus einem Backup wiederherstellen.")
elif services_stopped:
restart_services(strict=False)
services_stopped = False
finally:
if archive_path and os.path.exists(archive_path):
os.remove(archive_path)
if staging_dir and os.path.exists(staging_dir):
shutil.rmtree(staging_dir, ignore_errors=True)
pause()
# ==========================================
# Einstellungen
# ==========================================
def settings_menu():
while True:
print_header("EINSTELLUNGEN")
keys = list(CONFIG.keys())
for index, key in enumerate(keys, 1):
value = "*****" if key == "db_pass" and CONFIG[key] else CONFIG[key]
print(
f" {Colors.BOLD}{index}.{Colors.ENDC} "
f"{key.ljust(15)}: {Colors.BLUE}{value}{Colors.ENDC}"
)
print(f"\n {Colors.BOLD}S.{Colors.ENDC} Speichern & zurück zum Hauptmenü")
choice = input("\nWelchen Wert möchtest du ändern? (Zahl/S): ").strip().lower()
if choice == "s":
break
if choice.isdigit() and 1 <= int(choice) <= len(keys):
key_to_edit = keys[int(choice) - 1]
current_display = "*****" if key_to_edit == "db_pass" and CONFIG[key_to_edit] else CONFIG[key_to_edit]
new_value = input(f"Neuer Wert für {key_to_edit} (aktuell: {current_display}): ")
if new_value.strip() != "":
CONFIG[key_to_edit] = new_value.strip()
# ==========================================
# Hauptmenü
# ==========================================
def main_menu():
while True:
print_header("NETBOX BACKUP, RESTORE & UPGRADE TOOL")
print(f" {Colors.BOLD}1.{Colors.ENDC} Backup erstellen")
print(f" {Colors.BOLD}2.{Colors.ENDC} Restore-Menü (Backup wiederherstellen)")
print(f" {Colors.BOLD}3.{Colors.ENDC} NetBox upgraden")
print(f" {Colors.BOLD}4.{Colors.ENDC} Einstellungen prüfen / anpassen")
print(f" {Colors.BOLD}5.{Colors.ENDC} Beenden\n")
choice = input(Colors.BOLD + "Wähle eine Aktion (1-5): " + Colors.ENDC).strip()
if choice == "1":
execute_backup()
elif choice == "2":
restore_menu()
elif choice == "3":
execute_upgrade()
elif choice == "4":
settings_menu()
elif choice == "5":
clear_screen()
print("Beendet. Auf Wiedersehen!\n")
sys.exit(0)
else:
log_error("Ungültige Eingabe.")
time.sleep(1)
if __name__ == "__main__":
if os.geteuid() != 0:
print(
Colors.WARNING
+ "Hinweis: Dieses Skript sollte idealerweise als 'root' oder mit 'sudo' ausgeführt werden,"
+ Colors.ENDC
)
print(
Colors.WARNING
+ "da systemctl, chown und der Zugriff auf /opt/netbox erhöhte Rechte erfordern.\n"
+ Colors.ENDC
)
time.sleep(2)
try:
main_menu()
except KeyboardInterrupt:
print("\n\nAbbruch durch Benutzer. Ciao!")
sys.exit(0)