Compare commits

...
Author SHA1 Message Date
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
MrBlakeandClaude Opus 5.5 c6dcb9567c Fix greenfield DB restore: force UTF-8 database, drop REASSIGN OWNED
- Create the database with UTF8 encoding (template0, C.UTF-8) so the
  ICU collation natural_sort works and core tables get created
- Remove REASSIGN OWNED BY postgres (fails on system objects)
- Show error count and first pg_restore errors instead of the full log
- Install systemd units right after the installation files

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 13:37:30 +01:00
MrBlakeandClaude Opus 5.5 a0e3feaff4 Fix greenfield restore: import DB as postgres and verify tables
- Greenfield restore runs dropdb/createdb/pg_restore as local postgres
  superuser with --role=db_user to avoid permission issues
- Abort before upgrade.sh if core NetBox tables are missing after import
- Install systemd units before upgrade.sh so error-path restarts work

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 13:33:34 +01:00
MrBlakeandClaude Opus 5.5 e3f550f17a Add optional greenfield installation to restore menu
New restore menu option sets up a fresh Debian/Ubuntu server (packages,
PostgreSQL role/database, Redis, netbox user, systemd units, optional
nginx with self-signed cert) and then runs a full restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 13:01:57 +01:00
MrBlake f132d8878d Merge branch 'feature/full-backup-restore-menu'
# Conflicts:
#	README.md
2026-11-06 08:41:47 +01:00
MrBlakeandClaude Opus 5.5 23f3141757 docs: translate README to English and align structure
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:58:22 +01:00
3 changed files with 458 additions and 28 deletions

No files matched your search

+24 -3
View File
@@ -348,8 +348,9 @@ Im Hauptmenü auswählen:
2. Nur Datenbank wiederherstellen
3. Nur Media-Dateien wiederherstellen
4. Nur Installationsdateien wiederherstellen
5. Backup-Inhalt anzeigen
6. Zurück zum Hauptmenü
5. Neuinstallation auf grüner Wiese (System einrichten + Komplett-Restore)
6. Backup-Inhalt anzeigen
7. Zurück zum Hauptmenü
```
Der Restore muss als `root` oder mit `sudo` ausgeführt werden.
@@ -381,6 +382,24 @@ Die aktuelle Installation wird nie gelöscht:
| `/opt/netbox` ist ein Verzeichnis | bisherige Installation wird zu `/opt/netbox_before_restore_<Zeitstempel>` umbenannt |
| `/opt/netbox` ist ein Symlink | Wiederherstellung nach `/opt/netbox-<Version>-restored-<Zeitstempel>`, Symlink wird atomar umgestellt |
### Neuinstallation auf grüner Wiese (optional)
Menüpunkt `5` stellt ein Backup auf einem frischen Debian/Ubuntu-Server ohne vorhandene NetBox-Installation wieder her. Das Backup muss Installationsdateien und Datenbank enthalten (Format-Version 1.3 oder neuer).
Vor dem eigentlichen Komplett-Restore richtet das Tool ein:
1. Systempakete per `apt-get` (PostgreSQL, Redis, Python inkl. `venv`/`dev`, Build-Abhängigkeiten, Git).
2. PostgreSQL-Rolle `db_user` (mit `LOGIN CREATEDB` und dem Passwort `db_pass`) und Datenbank `db_name`. Ist `db_pass` leer, wird es abgefragt.
3. Systembenutzer `netbox`, falls nicht vorhanden.
Nach Wiederherstellung und `upgrade.sh`:
4. `gunicorn.py` und die systemd-Units aus `contrib/` nach `/etc/systemd/system` kopieren (bestehende werden nicht überschrieben) und aktivieren.
5. Optional nginx mit `contrib/nginx.conf` und einem selbstsignierten Zertifikat (`/etc/ssl/certs/netbox.crt`) einrichten.
> [!IMPORTANT]
> `db_name`, `db_user`, `db_pass` und `netbox_path` müssen zur `configuration.py` im Backup passen. `db_host` muss `localhost` sein. Das selbstsignierte Zertifikat später durch ein echtes ersetzen.
### Ältere Backups
Backups vor Format-Version 1.3 enthalten keine Installationsdateien, lassen sich aber weiterhin wiederherstellen.
@@ -416,7 +435,9 @@ Meldungen von `pg_restore` werden angezeigt. Da PostgreSQL auch bei einzelnen Wa
### Media-Dateien
Vorhandene Media-Dateien unter folgendem Pfad werden ersetzt:
Beim Backup fragt das Tool NetBox selbst (über `manage.py shell` im venv) nach dem tatsächlichen `MEDIA_ROOT` und nach allen Dateien, die Modelle – auch von Plugins – über ein `FileField` referenzieren (Ansatz wie im Plugin [NetBox-Export](https://git.mrblake.cc/MrBlake/NetBox-Export)). Dateien außerhalb von `MEDIA_ROOT` werden zusätzlich unter `extra_files/` gesichert und beim Restore an ihren ursprünglichen Pfad zurückgeschrieben (Pfade innerhalb der alten Installation werden auf die aktuelle abgebildet). Fehlende Dateien und Dateien in externen Storages (z. B. S3) werden als Warnung gemeldet. Ohne venv (z. B. defekte Installation) wird nur `MEDIA_ROOT` gesichert.
Vorhandene Media-Dateien unter folgendem Pfad (bzw. dem gesicherten `MEDIA_ROOT`) werden ersetzt:
```text
/opt/netbox/netbox/media
+22 -3
View File
@@ -238,7 +238,7 @@ Main menu → `1. Backup erstellen`.
The tool asks which components to back up:
1. **PostgreSQL database** (`pg_dump -Fc`)
2. **Media files** (`netbox/media/`)
2. **Media files** (`MEDIA_ROOT`, default `netbox/media/`). The tool also asks NetBox (via `manage.py shell` in the venv) for every file referenced by a model `FileField` – including plugins, same approach as [NetBox-Export](https://git.mrblake.cc/MrBlake/NetBox-Export). Files outside `MEDIA_ROOT` are stored under `extra_files/` and written back to their original path on restore. Missing files and files in external storages (e.g. S3) are reported as warnings.
3. **Installation files** – a complete copy of the NetBox installation directory
The installation files contain everything in the (resolved) `netbox_path`, for example:
@@ -320,8 +320,9 @@ Main menu → `2. Restore-Menü`.
2. Nur Datenbank wiederherstellen (database only)
3. Nur Media-Dateien wiederherstellen (media only)
4. Nur Installationsdateien wiederherstellen (installation files only)
5. Backup-Inhalt anzeigen (show backup contents)
6. Zurück zum Hauptmenü (back)
5. Neuinstallation auf grüner Wiese (...) (greenfield install + full restore)
6. Backup-Inhalt anzeigen (show backup contents)
7. Zurück zum Hauptmenü (back)
```
Restore must be run as `root` / with `sudo`.
@@ -357,6 +358,24 @@ The current installation is never deleted:
| `/opt/netbox` is a directory | current installation is renamed to `/opt/netbox_before_restore_<timestamp>`, the restored files take its place |
| `/opt/netbox` is a symlink | restored files go to `/opt/netbox-<version>-restored-<timestamp>`, the symlink is switched atomically; the previous target stays |
### Greenfield installation (optional)
Menu item `5` restores a backup onto a fresh Debian/Ubuntu server with no existing NetBox. The backup must contain installation files and the database (format 1.3 or newer).
Before the full restore, the tool sets up:
1. System packages via `apt-get` (PostgreSQL, Redis, Python incl. `venv`/`dev`, build dependencies, Git).
2. PostgreSQL role `db_user` (`LOGIN CREATEDB`, password `db_pass`) and database `db_name`. If `db_pass` is empty, it is prompted for.
3. System user `netbox`, if missing.
After the restore and `upgrade.sh`:
4. `gunicorn.py` and the systemd units from `contrib/` are copied to `/etc/systemd/system` (existing ones are not overwritten) and enabled.
5. Optionally nginx using `contrib/nginx.conf` with a self-signed certificate (`/etc/ssl/certs/netbox.crt`).
> [!IMPORTANT]
> `db_name`, `db_user`, `db_pass` and `netbox_path` must match the `configuration.py` in the backup, and `db_host` must be `localhost`. Replace the self-signed certificate with a real one later.
### Required database privileges
The configured database user must be allowed to run `dropdb` and `createdb`.
+412 -22
View File
@@ -45,7 +45,7 @@ DEFAULT_PLUGIN_REQUIREMENTS = (
)
LDAP_REQUIREMENT = "django-auth-ldap"
BACKUP_FORMAT_VERSION = "1.3"
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")
@@ -271,6 +271,70 @@ def collect_installation_files(root):
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,
@@ -336,8 +400,14 @@ def create_backup(
# 2. Media-Dateien
media_files = []
extra_files = []
file_scan = None
if do_media:
log_info("Schritt 2: Sammle Media-Dateien (Bilder, Dokumente)...")
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:
@@ -348,6 +418,28 @@ def create_backup(
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.")
@@ -379,6 +471,8 @@ def create_backup(
"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,
}
@@ -395,6 +489,8 @@ def create_backup(
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:
@@ -474,6 +570,8 @@ def show_backup_info(path, meta):
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'))}")
@@ -570,10 +668,71 @@ def restore_installation_files(extract_dir, meta, stamp, keep_current_media):
return {"mode": "directory", "old_path": old_path, "new_path": netbox_path}
def restore_database(dump_file):
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"]
@@ -627,19 +786,50 @@ def restore_database(dump_file):
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(source_media):
media_path = os.path.join(CONFIG["netbox_path"], "netbox", "media")
if not os.path.isdir(source_media):
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.")
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.")
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():
@@ -667,10 +857,181 @@ RESTORE_COMPONENT_LABELS = {
"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 execute_restore(components=None):
"""Stellt die gewählten Komponenten wieder her (None = alles, was im Backup enthalten ist)."""
print_header("RESTORE PROZESS")
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.")
@@ -699,8 +1060,17 @@ def execute_restore(components=None):
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 = (
@@ -735,6 +1105,14 @@ def execute_restore(components=None):
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
@@ -750,14 +1128,20 @@ def execute_restore(components=None):
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"))
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(os.path.join(tmp_extract_dir, "media"))
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)...")
@@ -769,6 +1153,10 @@ def execute_restore(components=None):
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)
@@ -803,18 +1191,20 @@ def restore_menu():
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")
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-6): " + Colors.ENDC).strip()
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": show_backup_details,
"5": execute_greenfield_restore,
"6": show_backup_details,
}
if choice == "6":
if choice == "7":
return
if choice in actions:
actions[choice]()