Compare commits

..
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 81ce2ab392 Add full installation backup, restore menu and pre-upgrade backup
- 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]>
2026-11-06 08:37:11 +01:00
MrBlake cb32ebd7d8 add readme 2026-07-20 12:42:56 +02:00
4 changed files with 2560 additions and 164 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
__pycache__/
+1114
View File
File diff suppressed because it is too large. Load diff
+873
View File
@@ -0,0 +1,873 @@
# NetBox Backup, Restore & Upgrade Tool
🇩🇪 [Deutsche Version](README.de.md)
An interactive Python tool for backing up, restoring and upgrading a NetBox installation on Linux.
The script combines the following tasks in a simple terminal interface:
- Back up the PostgreSQL database
- Back up NetBox media files
- Back up the complete installation files (configuration, `local_requirements.txt`, LDAP settings, scripts, reports, ...)
- Store everything in a single ZIP file
- Restore everything or individual components (database, media, installation files) via a restore menu
- Download and install new NetBox releases
- Automatically create a full backup before every upgrade
- Carry over configuration, LDAP settings, plugins, media files, reports and custom scripts
- Stop, start and verify the NetBox services
- Keep the previous installation for a possible rollback
> [!IMPORTANT]
> This project is not an official tool of the NetBox project. Test backup, restore and upgrade on a test instance first. Always keep a current backup stored on another system before upgrading.
---
## Table of contents
1. [Requirements](#requirements)
2. [Installation](#installation)
3. [Quick start](#quick-start)
4. [Configuration](#configuration)
5. [Creating a backup](#creating-a-backup)
6. [Restore menu](#restore-menu)
7. [Upgrading NetBox](#upgrading-netbox)
8. [Files and directories carried over](#files-and-directories-carried-over)
9. [Plugins and LDAP](#plugins-and-ldap)
10. [CSRF trusted origins](#csrf-trusted-origins)
11. [Rollback behaviour](#rollback-behaviour)
12. [Backup layout](#backup-layout)
13. [Troubleshooting](#troubleshooting)
14. [Security notes](#security-notes)
15. [Known limitations](#known-limitations)
---
## Requirements
### Operating system
The tool targets a classic NetBox installation on Linux. Restore and upgrade require:
- Linux or another POSIX system
- `systemd`
- root privileges
- write access to `/opt` (or the parent directory of `netbox_path`)
- internet access to GitHub (upgrade only)
### Python
- Python 3.8 or newer recommended
- Only modules from the Python standard library are used
- No additional Python packages are required for the tool itself
### System programs
| Program | Purpose |
|---|---|
| `pg_dump` | Back up the PostgreSQL database (also required for the automatic pre-upgrade backup) |
| `pg_restore` | Restore a PostgreSQL dump |
| `dropdb` | Drop the existing target database during restore |
| `createdb` | Re-create the target database |
| `systemctl` | Stop and start the NetBox services |
| `cp` | Carry over configuration and local data during upgrade |
| `chown` | Set the owner of restored media files |
| `git` | Optional, used to detect the installed NetBox version |
On Debian or Ubuntu the PostgreSQL client programs are provided by the `postgresql-client` package.
### NetBox directory layout
By default the tool expects NetBox in:
```text
/opt/netbox
```
Among others, these paths are expected:
```text
/opt/netbox/upgrade.sh
/opt/netbox/netbox/netbox/configuration.py
/opt/netbox/netbox/media/
```
`/opt/netbox` may be a regular directory or a symlink to a version-specific directory.
### NetBox services
The script uses these service names by default:
```text
netbox
netbox-rq
```
If your unit names differ, adjust the `NETBOX_SERVICES` constant in the script.
---
## Installation
Copy the script to `/usr/local/sbin` or another suitable directory:
```bash
sudo cp nettmanage.py /usr/local/sbin/netbox-tool
sudo chmod 700 /usr/local/sbin/netbox-tool
sudo chown root:root /usr/local/sbin/netbox-tool
```
Then run it:
```bash
sudo /usr/local/sbin/netbox-tool
```
Or run it directly from the current directory:
```bash
chmod +x nettmanage.py
sudo ./nettmanage.py
```
Optionally check the Python syntax first:
```bash
python3 -m py_compile nettmanage.py
```
---
## Quick start
After starting, the main menu appears (the user interface is in German):
```text
============================================================
NETBOX BACKUP, RESTORE & UPGRADE TOOL
============================================================
1. Backup erstellen (create backup)
2. Restore-Menü (Backup wiederherstellen) (restore menu)
3. NetBox upgraden (upgrade NetBox)
4. Einstellungen prüfen / anpassen (settings)
5. Beenden (exit)
```
Recommended order before an upgrade:
1. Check the settings, especially `backup_dir`.
2. Read the release notes of the target version.
3. Check plugin compatibility.
4. Start the upgrade – a full backup is created automatically.
5. Copy the pre-upgrade backup to another system.
6. Check the web UI, worker, plugins and logs.
---
## Configuration
The defaults are defined at the top of the script:
```python
CONFIG = {
"netbox_path": "/opt/netbox",
"db_host": "localhost",
"db_name": "netbox",
"db_user": "netbox",
"db_pass": "",
"backup_dir": "/tmp",
"python_path": "",
}
```
### Configuration values
| Key | Description | Default |
|---|---|---|
| `netbox_path` | Active NetBox installation path | `/opt/netbox` |
| `db_host` | PostgreSQL server | `localhost` |
| `db_name` | Name of the NetBox database | `netbox` |
| `db_user` | PostgreSQL user | `netbox` |
| `db_pass` | PostgreSQL password | empty |
| `backup_dir` | Target for backups and temporary files; the restore menu lists backups found here | `/tmp` |
| `python_path` | Optional Python interpreter for `upgrade.sh` | empty |
### Python version for the upgrade
Normally `upgrade.sh` uses the appropriate default interpreter. If a specific Python version is required:
```python
"python_path": "/usr/bin/python3.12",
```
The script then sets the `PYTHON` environment variable when calling `upgrade.sh`.
### Database password
If `db_pass` is set, it is passed to PostgreSQL commands via the `PGPASSWORD` environment variable.
A PostgreSQL password file is usually the better choice:
```text
/root/.pgpass
```
Example:
```text
localhost:5432:netbox:netbox:MY_PASSWORD
```
```bash
chmod 600 /root/.pgpass
```
`db_pass` can then stay empty.
> [!NOTE]
> Changes made via the **settings** menu only apply to the running process. They are not saved. For permanent changes edit the `CONFIG` block in the script.
---
## Creating a backup
Main menu → `1. Backup erstellen`.
### Components
The tool asks which components to back up:
1. **PostgreSQL database** (`pg_dump -Fc`)
2. **Media files** (`netbox/media/`)
3. **Installation files** – a complete copy of the NetBox installation directory
The installation files contain everything in the (resolved) `netbox_path`, for example:
- `netbox/netbox/configuration.py`
- `netbox/netbox/ldap_config.py`
- `local_requirements.txt`
- `gunicorn.py`
- `netbox/scripts/`, `netbox/reports/`
- `upgrade.sh` and the NetBox source code of the installed version
Excluded, because they are re-created by `upgrade.sh` or backed up separately:
```text
venv/ (virtual environment, re-created by upgrade.sh)
netbox/static/ (collectstatic output, re-created by upgrade.sh)
netbox/media/ (backed up as its own component)
__pycache__/
```
File permissions, owners and symlinks are recorded in `files_manifest.json` inside the archive and re-applied on restore.
### Excluding the change log
```text
Changelog (extras_objectchange) auslassen? Spart viel Platz. (j/N)
```
The table structure stays in the dump, only its data is skipped. This can reduce the backup size considerably.
### Excluding users
The data of these tables is not exported:
```text
auth_user
auth_group
users_token
```
> [!WARNING]
> Excluding users can cause foreign key errors or missing assignments on restore. Only use this option if the target system already has matching users or you know the consequences.
### Backup file
```text
netbox_backup_YYYYMMDD_HHMMSS.zip
```
Example:
```text
/tmp/netbox_backup_20260720_143500.zip
```
The ZIP file is created with mode `600` (readable by root only), because it contains the database dump and `configuration.py` including `SECRET_KEY` and database credentials.
### Verifying the backup
```bash
ls -lh /tmp/netbox_backup_*.zip
unzip -l /tmp/netbox_backup_20260720_143500.zip
sha256sum /tmp/netbox_backup_20260720_143500.zip
scp /tmp/netbox_backup_20260720_143500.zip backupserver:/srv/backups/netbox/
```
The contents can also be shown via restore menu → `5. Backup-Inhalt anzeigen`.
Do not keep backups only in `/tmp`; depending on the system it may be cleared on reboot.
---
## Restore menu
Main menu → `2. Restore-Menü`.
```text
1. Komplett-Restore (alles, was im Backup enthalten ist) (full restore)
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)
```
Restore must be run as `root` / with `sudo`.
> [!CAUTION]
> A restore overwrites the data of the instance. When restoring the database, the configured PostgreSQL database is dropped and re-created.
### Selecting a backup
All `netbox_*.zip` files in `backup_dir` are listed, newest first, with size and date. Select one by number or enter any path to a backup ZIP file.
Before confirming, the tool shows the backup's metadata (date, NetBox version, contained components). If you restore only the database and it comes from a **newer** NetBox version than the installed one, a warning is shown – in that case also restore the installation files.
### Process
1. Extract the archive into a temporary directory inside `backup_dir`.
2. Stop `netbox` and `netbox-rq`.
3. Restore the selected components:
- **Installation files:** extracted to a new directory, permissions/owners/symlinks re-applied, then switched in (see below). If media is not restored at the same time, the current media files are copied into the restored installation.
- **Database:** `dropdb`, `createdb`, `pg_restore`.
- **Media:** replace `netbox/media/` and set the owner to `netbox:netbox`.
4. Run `upgrade.sh` (only if database or installation files were restored). This re-creates the venv, installs `local_requirements.txt`, runs migrations and collects static files.
5. Restart and verify the services.
If an error occurs, the tool tries to start the services again.
### Restoring installation files
The current installation is never deleted:
| Layout | Behaviour |
|---|---|
| `/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 |
### Required database privileges
The configured database user must be allowed to run `dropdb` and `createdb`.
```bash
sudo -u postgres psql -c "\du"
```
### pg_restore
The dump is imported roughly like this:
```bash
pg_restore -h localhost -U netbox -d netbox --clean --if-exists --no-owner netbox_database.dump
```
Because PostgreSQL may return a non-zero exit code for individual warnings, the tool reports the restore as completed and prints the messages. Check the database and NetBox logs afterwards.
### Backups from older tool versions
Backups created before format version 1.3 contain no installation files. They can still be restored; options 1–3 work as before, option 4 reports that the component is missing.
---
## Upgrading NetBox
Main menu → `3. NetBox upgraden`. Must be run as `root` / with `sudo`.
### Target version
The version can be entered with or without a leading `v` (`4.6.5` or `v4.6.5`). Only stable versions in the format `X.Y.Z` are accepted; pre-releases such as `4.6.0-beta1` are rejected.
### Version check
The installed version is detected via:
- the name of the real installation directory
- an exact Git tag
- the NetBox Python package in the existing venv
- NetBox version files
The target version must be higher than the installed version. Downgrades are not automated. A major version jump triggers an additional warning.
### Automatic pre-upgrade backup
Before anything is changed, the tool creates a **full backup** (database, media and installation files):
```text
netbox_pre_upgrade_vX.Y.Z_YYYYMMDD_HHMMSS.zip
```
in `backup_dir`. If `pg_dump` is missing or the backup fails, the upgrade is aborted before anything is changed.
Skipping the backup is possible but requires typing `OHNE BACKUP` explicitly.
If the upgrade fails after `upgrade.sh` was started, the tool prints the path of this backup so it can be restored via restore menu → `1. Komplett-Restore`.
### Upgrade process
1. Validate the target version.
2. Check the existing NetBox installation.
3. Ask for confirmation that the release notes were read.
4. Ask whether to skip the automatic backup (default: no).
5. Optionally add the preconfigured plugins.
6. Detect the LDAP configuration.
7. Check or add `CSRF_TRUSTED_ORIGINS`.
8. **Create the full pre-upgrade backup.**
9. Download the release archive from GitHub.
10. Safely extract and verify the TAR archive.
11. Carry over local files and directories.
12. Stop the services.
13. Switch the installation directory or symlink.
14. Run `/opt/netbox/upgrade.sh`.
15. Restart the services and verify their status.
16. Keep the old installation as a fallback.
### Download URL
```text
https://github.com/netbox-community/netbox/archive/refs/tags/vX.Y.Z.tar.gz
```
The temporary archive is deleted after the upgrade.
### Downtime
Backup, download, extraction and preparation happen before the services are stopped. Downtime starts with the switch to the new installation.
---
## Files and directories carried over
During the upgrade, these items are copied from the existing installation into the new release.
### Mandatory file
```text
netbox/netbox/configuration.py
```
If it is missing, the upgrade is aborted.
### Optional files
```text
netbox/netbox/ldap_config.py
local_requirements.txt
gunicorn.py
```
### Optional directories
```text
netbox/media/
netbox/scripts/
netbox/reports/
```
Copied with `cp -a`, preserving permissions, timestamps and symlinks.
### Not carried over automatically
Manual changes to NetBox source files (templates, Python files, static files outside the paths above) are not detected or merged during the upgrade. They are, however, part of the installation files backup. Implement such changes as a plugin, custom script or documented deployment step.
---
## Plugins and LDAP
### Existing requirements
An existing `/opt/netbox/local_requirements.txt` is copied into the new release. Existing entries are kept unchanged. The tool detects package names and does not add a package again if an unversioned or pinned entry already exists:
```text
netbox-topology-views
netbox-topology-views==4.2.1
netbox_topology_views>=4.0
```
### Preconfigured plugins
On request the tool adds:
```text
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
```
The list is defined in `DEFAULT_PLUGIN_REQUIREMENTS` and can be adapted.
### LDAP
If `/opt/netbox/netbox/netbox/ldap_config.py` exists:
1. `ldap_config.py` is copied into the new installation.
2. `django-auth-ldap` is ensured in `local_requirements.txt`.
### Plugin compatibility
The tool cannot reliably check whether a plugin supports the target NetBox version. This is checked at the latest when `upgrade.sh` installs the requirements. Before upgrading, check for each plugin:
- supported NetBox version
- supported Python version
- required migration steps
- changed configuration values
- known incompatibilities
An incompatible plugin can abort `upgrade.sh` or prevent NetBox from starting.
---
## CSRF trusted origins
The tool checks whether `configuration.py` contains a direct assignment:
```python
CSRF_TRUSTED_ORIGINS = [
"https://netbox.example.local",
]
```
During the upgrade, new origins can be entered comma-separated:
```text
https://netbox.example.local,http://192.168.1.50
```
Only origins with `http://` or `https://`, a host name or IP, an optional port and no path, query or fragment are accepted.
Valid:
```text
https://netbox.example.local
http://192.168.1.50
https://netbox.example.local:8443
```
Invalid:
```text
netbox.example.local
https://netbox.example.local/netbox
https://netbox.example.local?test=1
```
New origins are appended as a new block to `configuration.py`:
```python
# Automatisch durch das NetBox-Upgrade-Tool gesetzt
CSRF_TRUSTED_ORIGINS = [
'https://netbox.example.local',
'http://192.168.1.50',
]
```
> [!NOTE]
> If a direct assignment already exists and new values are entered, the file contains two assignments afterwards; the last one wins. Review and consolidate the file after the upgrade.
Dynamically imported or computed CSRF settings may not be detected. In that case the tool warns and asks for an extra confirmation.
---
## Rollback behaviour
### Error before `upgrade.sh` starts
If the error occurs after the directory switch but before `upgrade.sh` starts, the tool automatically:
1. re-activates the previous installation,
2. restarts the NetBox services.
No database migrations of the new release have run at this point.
### Error after `upgrade.sh` started
Once `upgrade.sh` has started, there is no automatic full rollback, because database migrations may already have been applied.
Full rollback using the restore menu:
1. Restore menu → `1. Komplett-Restore`.
2. Select the `netbox_pre_upgrade_v…` backup.
3. The tool stops the services, restores installation files, database and media, runs `upgrade.sh` of the old version and restarts the services.
4. Check the logs.
### Regular directory
The old installation is kept, e.g. at:
```text
/opt/netbox_old_20260720_143500
```
If the name exists, a running number is appended.
### Symlink installation
The new release is installed, e.g. at `/opt/netbox-4.6.5`, and the `/opt/netbox` symlink is switched atomically. The previous release directory remains. If `/opt/netbox-4.6.5` already exists, the tool aborts.
---
## Backup layout
```text
netbox_backup_YYYYMMDD_HHMMSS.zip
├── metadata.json
├── netbox_database.dump (database)
├── media/ (media files)
├── files_manifest.json (permissions, owners, symlinks of the installation files)
└── files/ (installation files)
├── upgrade.sh
├── local_requirements.txt
├── gunicorn.py
└── netbox/
├── netbox/configuration.py
├── netbox/ldap_config.py
├── scripts/
└── reports/
```
Depending on the chosen scope, individual parts may be missing.
### Metadata
```json
{
"version": "1.3",
"timestamp": "20260720_143500",
"source_db": "netbox",
"netbox_path": "/opt/netbox",
"netbox_root": "/opt/netbox-4.6.4",
"netbox_version": "4.6.4",
"contains_db": true,
"contains_media": true,
"contains_files": true,
"excluded_changelog": false,
"excluded_users": false
}
```
The restore uses this file to determine the contained components.
### Safe extraction
ZIP and TAR paths are checked before extraction to prevent path traversal. TAR archives with symlinks or hard links are rejected. Symlinks of the installation are not stored in the ZIP but re-created from the manifest. Only use backups and release archives from trusted sources.
---
## Troubleshooting
### `pg_dump: command not found`
```bash
sudo apt update
sudo apt install postgresql-client
```
Use a client version matching the server. Without `pg_dump` the upgrade aborts, because the automatic backup cannot be created.
### PostgreSQL asks for a password
- set `db_pass` in the script
- configure `/root/.pgpass`
- configure local PostgreSQL authentication
### `dropdb` or `createdb` fails
The configured user probably lacks the required privileges:
```bash
sudo -u postgres psql -c "\du"
```
### Restore: "Dienst ... läuft trotz Stop-Befehl weiter"
A service could not be stopped. Check `systemctl status netbox netbox-rq` and stop it manually before retrying.
### Target version not found
```text
NetBox-Release vX.Y.Z wurde auf GitHub nicht gefunden.
```
Check the spelling, internet access, DNS, proxy/firewall rules and whether the release exists.
### Download fails behind a proxy
```bash
export HTTPS_PROXY=http://proxy.example.local:3128
export HTTP_PROXY=http://proxy.example.local:3128
sudo -E ./nettmanage.py
```
Be aware of the security implications of `sudo -E`.
### `configuration.py` is missing
The tool expects `/opt/netbox/netbox/netbox/configuration.py`. Check `CONFIG["netbox_path"]`.
### Service does not start after upgrade or restore
```bash
systemctl status netbox --no-pager -l
systemctl status netbox-rq --no-pager -l
journalctl -u netbox -n 200 --no-pager
journalctl -u netbox-rq -n 200 --no-pager
```
Common causes: incompatible plugin, wrong Python version, missing system library, errors in `configuration.py` or `ldap_config.py`, incomplete migrations, wrong file permissions, changed configuration options.
### `upgrade.sh` fails because of a plugin
Temporarily comment out or remove the plugin in `local_requirements.txt`, if that is acceptable for the migration, then install a compatible version. Make sure a full backup exists first.
### Wrong Python interpreter
```python
"python_path": "/usr/bin/python3.12",
```
```bash
/usr/bin/python3.12 --version
```
### Media files have wrong permissions
```bash
sudo chown -R netbox:netbox /opt/netbox/netbox/media
```
### Upgrade or restore interrupted with Ctrl+C
The program exits. If `upgrade.sh` had already started, do not assume a rollback happened:
1. Check the service status.
2. Check for running upgrade, pip or migration processes.
3. Check the installation path and symlink target.
4. Do not reset the database schema without a backup.
5. Review the output and logs.
---
## Security notes
### Root privileges
Backups may work without root depending on file permissions. Restore and upgrade require root for `/opt/netbox`, `systemctl`, `chown` and the directory switch.
### Passwords in the source code
A database password in the `CONFIG` block is readable by anyone who can read the script. Prefer `.pgpass`, make the script readable by root only and never commit credentials.
```bash
sudo chown root:root /usr/local/sbin/netbox-tool
sudo chmod 700 /usr/local/sbin/netbox-tool
```
### Protecting backups
A backup contains sensitive data: user accounts, API tokens, device and location data, IP addresses, plugin secrets, documents and images, and – with installation files – `configuration.py` including `SECRET_KEY` and database credentials.
Backups are created with mode `600`. They should also be transferred and stored encrypted, be accessible only to authorised persons and be deleted according to a retention plan.
### `/tmp` as backup target
`/tmp` is convenient as a default but not suitable as permanent backup storage. Change `backup_dir`, for example:
```python
"backup_dir": "/srv/backups/netbox",
```
```bash
sudo install -d -m 700 -o root -g root /srv/backups/netbox
```
### Release and plugin sources
The NetBox release is downloaded from GitHub, one plugin requirement points to an external Git server. Check trust, availability, TLS, version/commit pinning and your supply chain policies.
---
## Known limitations
- Settings changed in the menu are not saved.
- Plugin compatibility is not checked in advance.
- Release notes are not read or interpreted automatically.
- Major upgrade paths are only warned about, not fully validated.
- An automatic database rollback after migrations started is intentionally not implemented; use the restore menu with the pre-upgrade backup.
- Backup and restore use the same configured database user.
- The service names `netbox` and `netbox-rq` are hard-coded.
- Additional services (housekeeping, reverse proxy, monitoring) are not restarted.
- Manual changes to the NetBox source are not carried over during upgrade (but are included in the installation files backup).
- New CSRF origins are appended as an additional block instead of editing an existing one.
- No automatic HTTP health check of the web UI.
- No automatic backup rotation – pre-upgrade backups accumulate in `backup_dir`.
- Backups are not encrypted automatically.
- The venv is not part of the backup; it is re-created by `upgrade.sh` on restore, which requires access to PyPI (or your package mirror).
---
## Recommended checks after an upgrade
```bash
systemctl status netbox netbox-rq --no-pager
journalctl -u netbox -u netbox-rq --since "15 minutes ago" --no-pager
```
In the web UI check that login, the start page, objects and IPAM data, images and documents, custom scripts and reports, background jobs, LDAP login, plugins and the API work.
Only remove the old installation and the backup once the new version has been verified and is stable.
---
## Example of a safe upgrade
```bash
# 1. Start the tool and choose menu item 3 (upgrade)
sudo /usr/local/sbin/netbox-tool
# -> a full backup is created automatically:
# /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip
# 2. Copy the backup to another system
scp /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip \
backupserver:/srv/backups/netbox/
# 3. Store a checksum
sha256sum /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip \
> /srv/backups/netbox/netbox_pre_upgrade_v4.6.5_20260720_143500.zip.sha256
# 4. Check services and logs
systemctl status netbox netbox-rq --no-pager
journalctl -u netbox -u netbox-rq --since "15 minutes ago" --no-pager
# If something is wrong: start the tool, menu 2 -> 1 (full restore)
# and select the pre-upgrade backup.
```
---
## Disclaimer
Use at your own risk. An upgrade can fail due to incompatible plugins, changed configuration options, database migrations, missing dependencies or local changes.
Before production changes, always have:
- a tested database backup
- a tested media backup
- a documented rollback plan
- a maintenance window
- access to the system and database console
- a tested restore on a separate instance
+572 -164
View File
@@ -3,6 +3,7 @@ import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tarfile
@@ -44,6 +45,12 @@ DEFAULT_PLUGIN_REQUIREMENTS = (
)
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
@@ -178,26 +185,115 @@ def execute_backup():
)
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:
if not do_db and not do_media and not do_files:
log_warn("Keine Komponenten zum Sichern ausgewählt. Abbruch.")
pause()
return
media_path = os.path.join(CONFIG["netbox_path"], "netbox/media")
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
archive_name = f"netbox_backup_{stamp}"
zip_file_path = os.path.join(CONFIG["backup_dir"], f"{archive_name}.zip")
tmp_dir = os.path.join(CONFIG["backup_dir"], f"nb_tmp_{stamp}")
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()
os.makedirs(tmp_dir, exist_ok=True)
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...")
dump_file = os.path.join(tmp_dir, "netbox_database.dump")
env = os.environ.copy()
if CONFIG["db_pass"]:
env["PGPASSWORD"] = CONFIG["db_pass"]
@@ -231,7 +327,6 @@ def execute_backup():
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.")
@@ -240,196 +335,439 @@ def execute_backup():
log_info("\nSchritt 1: Datenbank-Backup übersprungen.")
# 2. Media-Dateien
media_files = []
if do_media:
log_info("Schritt 2: Kopiere Media-Dateien (Bilder, Dokumente)...")
if os.path.exists(media_path):
dst_media = os.path.join(tmp_dir, "media")
shutil.copytree(media_path, dst_media, dirs_exist_ok=True)
log_success("Media-Ordner erfolgreich gesichert.")
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. Metadaten
log_info("Schritt 3: Erstelle Metadaten...")
# 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": "1.2",
"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,
}
with open(os.path.join(tmp_dir, "metadata.json"), "w", encoding="utf-8") as file_handle:
json.dump(meta, file_handle, indent=4)
# 4. ZIP erstellen
log_info(f"Schritt 4: Komprimiere Daten nach {zip_file_path} ...")
with zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(tmp_dir):
for filename in files:
full_path = os.path.join(root, filename)
rel_path = os.path.relpath(full_path, tmp_dir)
zipf.write(full_path, rel_path)
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}")
# 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)
pause()
return zip_file_path
def execute_restore():
# ==========================================
# 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")
log_warn("ACHTUNG: Dieser Vorgang überschreibt bestehende Daten auf der Ziel-Instanz!")
confirm = input("Bist du sicher, dass du fortfahren möchtest? (j/N): ")
if confirm.lower() != "j":
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
restore_file = input("\nPfad zur Backup-ZIP-Datei (z. B. /tmp/netbox_backup.zip): ").strip()
if not restore_file or not os.path.exists(restore_file):
log_error(f"Die Datei '{restore_file}' existiert nicht!")
pause()
return
media_path = os.path.join(CONFIG["netbox_path"], "netbox/media")
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
tmp_extract_dir = f"/tmp/nb_restore_{stamp}"
os.makedirs(tmp_extract_dir, exist_ok=True)
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)
meta_file = os.path.join(tmp_extract_dir, "metadata.json")
if not os.path.exists(meta_file):
raise RuntimeError("Ungültiges Backup: metadata.json fehlt.")
log_info("Schritt 2: Stoppe NetBox-Dienste...")
stop_services()
services_stopped = True
with open(meta_file, "r", encoding="utf-8") as file_handle:
meta = json.load(file_handle)
# 2. Datenbank-Restore
if meta.get("contains_db", True):
log_info("Schritt 2: Stelle PostgreSQL-Datenbank wieder her...")
dump_file = os.path.join(tmp_extract_dir, "netbox_database.dump")
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 "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,
)
if drop_proc.returncode != 0:
raise RuntimeError(f"dropdb fehlgeschlagen: {drop_proc.stderr.strip()}")
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']}")
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()}")
if "db" in selected:
log_info("Schritt 3b: Stelle PostgreSQL-Datenbank wieder her...")
restore_database(os.path.join(tmp_extract_dir, "netbox_database.dump"))
log_info("Importiere Dump...")
proc_restore = run_command(
[
"pg_restore",
"-h",
CONFIG["db_host"],
"-U",
CONFIG["db_user"],
"-d",
CONFIG["db_name"],
"--clean",
"--no-owner",
dump_file,
],
env=env,
capture=True,
)
if "media" in selected:
log_info("Schritt 3c: Stelle Media-Dateien wieder her...")
restore_media(os.path.join(tmp_extract_dir, "media"))
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.")
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 2: Übersprungen (Keine Datenbank im Backup enthalten).")
log_info("Schritt 4: upgrade.sh nicht erforderlich (nur Media wiederhergestellt).")
# 3. Media-Restore
if meta.get("contains_media", True):
log_info("Schritt 3: Stelle Media-Dateien wieder her...")
src_media = os.path.join(tmp_extract_dir, "media")
if os.path.exists(src_media):
if os.path.exists(media_path):
shutil.rmtree(media_path)
shutil.copytree(src_media, media_path, dirs_exist_ok=True)
run_command(["chown", "-R", "netbox:netbox", media_path], capture=True)
log_success("Media-Dateien wiederhergestellt.")
else:
log_warn("Backup enthält laut Metadaten Media-Dateien, der Ordner fehlt jedoch.")
else:
log_info("Schritt 3: Übersprungen (Keine Media-Dateien im Backup enthalten).")
# 4. NetBox upgrade.sh
log_info("Schritt 4: Führe NetBox upgrade.sh aus (Cache-Clear & Migrationen)...")
upgrade_script = os.path.join(CONFIG["netbox_path"], "upgrade.sh")
if os.path.exists(upgrade_script):
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.")
else:
log_warn(f"Kein upgrade.sh unter {upgrade_script} gefunden.")
# 5. Services-Restart
log_info("Schritt 5: Starte NetBox-Dienste neu...")
restart_services(strict=True)
services_stopped = False
print("\n" + "=" * 60)
log_success("RESTORE ERFOLGREICH ABGESCHLOSSEN!")
@@ -437,12 +775,54 @@ def execute_restore():
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
# ==========================================
@@ -864,13 +1244,24 @@ def execute_upgrade():
)
print()
log_warn("Vor jedem Upgrade sind ein aktuelles Datenbank-/Media-Backup und die Release Notes Pflicht.")
log_info(f"Release Notes: https://github.com/netbox-community/netbox/releases/tag/v{target_version}")
if input("Backup erstellt und Release Notes geprüft? (j/N): ").strip().lower() != "j":
log_info("Upgrade abgebrochen. Bitte zuerst Backup und Release Notes prüfen.")
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()
@@ -929,6 +1320,7 @@ def execute_upgrade():
switch_state = None
services_stopped = False
upgrade_started = False
backup_file = None
try:
if not shutil.which("cp"):
@@ -937,6 +1329,16 @@ def execute_upgrade():
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",
@@ -1053,7 +1455,13 @@ def execute_upgrade():
"Datenbank-Migrationen könnten bereits angewendet worden sein."
)
log_info(f"Vorherige Installation liegt weiterhin unter: {switch_state['old_path']}")
log_info("Für einen vollständigen Rollback Datenbank/Media aus dem Backup wiederherstellen.")
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
@@ -1102,7 +1510,7 @@ 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} Backup wiederherstellen")
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")
@@ -1112,7 +1520,7 @@ def main_menu():
if choice == "1":
execute_backup()
elif choice == "2":
execute_restore()
restore_menu()
elif choice == "3":
execute_upgrade()
elif choice == "4":