- Backups can now include a complete copy of the NetBox installation files (configuration, local_requirements.txt, LDAP, scripts, reports) with permissions, owners and symlinks recorded in a manifest - New restore menu: full restore or database/media/installation files individually, backup selection from backup_dir, backup info view - Restore stops services before touching the database and keeps the previous installation when restoring files - Upgrade automatically creates a full backup before any change - Backup ZIPs are created with mode 600 - English README, German README moved to README.de.md and updated Co-Authored-By: Claude Opus 5.5 <[email protected]>
1555 lines
57 KiB
Python
1555 lines
57 KiB
Python
#!/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.3"
|
|
# 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
|
|
|
|
|
|
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 = []
|
|
if do_media:
|
|
log_info("Schritt 2: Sammle Media-Dateien (Bilder, Dokumente)...")
|
|
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.")
|
|
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,
|
|
"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}")
|
|
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'))}")
|
|
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(dump_file):
|
|
if not os.path.exists(dump_file):
|
|
raise RuntimeError("Ungültiges Backup: netbox_database.dump fehlt.")
|
|
|
|
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()}"
|
|
)
|
|
log_success("Datenbank-Wiederherstellung abgeschlossen.")
|
|
|
|
|
|
def restore_media(source_media):
|
|
media_path = os.path.join(CONFIG["netbox_path"], "netbox", "media")
|
|
if not os.path.isdir(source_media):
|
|
log_warn("Backup enthält laut Metadaten Media-Dateien, der Ordner fehlt jedoch.")
|
|
return
|
|
if os.path.exists(media_path):
|
|
shutil.rmtree(media_path)
|
|
shutil.copytree(source_media, media_path)
|
|
run_command(["chown", "-R", "netbox:netbox", media_path], capture=True)
|
|
log_success("Media-Dateien 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",
|
|
}
|
|
|
|
|
|
def execute_restore(components=None):
|
|
"""Stellt die gewählten Komponenten wieder her (None = alles, was im Backup enthalten ist)."""
|
|
print_header("RESTORE PROZESS")
|
|
|
|
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
|
|
|
|
show_backup_info(restore_file, meta)
|
|
|
|
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)
|
|
|
|
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 "db" in selected:
|
|
log_info("Schritt 3b: Stelle PostgreSQL-Datenbank wieder her...")
|
|
restore_database(os.path.join(tmp_extract_dir, "netbox_database.dump"))
|
|
|
|
if "media" in selected:
|
|
log_info("Schritt 3c: Stelle Media-Dateien wieder her...")
|
|
restore_media(os.path.join(tmp_extract_dir, "media"))
|
|
|
|
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
|
|
|
|
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} Backup-Inhalt anzeigen")
|
|
print(f" {Colors.BOLD}6.{Colors.ENDC} Zurück zum Hauptmenü\n")
|
|
|
|
choice = input(Colors.BOLD + "Wähle eine Aktion (1-6): " + 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": show_backup_details,
|
|
}
|
|
if choice == "6":
|
|
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) |