- 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]>
NetBox Backup, Restore & Upgrade Tool
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
- Requirements
- Installation
- Quick start
- Configuration
- Creating a backup
- Restore menu
- Upgrading NetBox
- Files and directories carried over
- Plugins and LDAP
- CSRF trusted origins
- Rollback behaviour
- Backup layout
- Troubleshooting
- Security notes
- 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 ofnetbox_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:
/opt/netbox
Among others, these paths are expected:
/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:
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:
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:
sudo /usr/local/sbin/netbox-tool
Or run it directly from the current directory:
chmod +x nettmanage.py
sudo ./nettmanage.py
Optionally check the Python syntax first:
python3 -m py_compile nettmanage.py
Quick start
After starting, the main menu appears (the user interface is in German):
============================================================
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:
- Check the settings, especially
backup_dir. - Read the release notes of the target version.
- Check plugin compatibility.
- Start the upgrade – a full backup is created automatically.
- Copy the pre-upgrade backup to another system.
- Check the web UI, worker, plugins and logs.
Configuration
The defaults are defined at the top of the script:
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_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:
/root/.pgpass
Example:
localhost:5432:netbox:netbox:MY_PASSWORD
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
CONFIGblock in the script.
Creating a backup
Main menu → 1. Backup erstellen.
Components
The tool asks which components to back up:
- PostgreSQL database (
pg_dump -Fc) - Media files (
netbox/media/) - 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.pynetbox/netbox/ldap_config.pylocal_requirements.txtgunicorn.pynetbox/scripts/,netbox/reports/upgrade.shand the NetBox source code of the installed version
Excluded, because they are re-created by upgrade.sh or backed up separately:
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
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:
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
netbox_backup_YYYYMMDD_HHMMSS.zip
Example:
/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
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ü.
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. 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.
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
- Extract the archive into a temporary directory inside
backup_dir. - Stop
netboxandnetbox-rq. - 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 tonetbox:netbox.
- Run
upgrade.sh(only if database or installation files were restored). This re-creates the venv, installslocal_requirements.txt, runs migrations and collects static files. - 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 |
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:
- System packages via
apt-get(PostgreSQL, Redis, Python incl.venv/dev, build dependencies, Git). - PostgreSQL role
db_user(LOGIN CREATEDB, passworddb_pass) and databasedb_name. Ifdb_passis empty, it is prompted for. - System user
netbox, if missing.
After the restore and upgrade.sh:
gunicorn.pyand the systemd units fromcontrib/are copied to/etc/systemd/system(existing ones are not overwritten) and enabled.- Optionally nginx using
contrib/nginx.confwith a self-signed certificate (/etc/ssl/certs/netbox.crt).
Important
db_name,db_user,db_passandnetbox_pathmust match theconfiguration.pyin the backup, anddb_hostmust belocalhost. 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.
sudo -u postgres psql -c "\du"
pg_restore
The dump is imported roughly like this:
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):
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
- Validate the target version.
- Check the existing NetBox installation.
- Ask for confirmation that the release notes were read.
- Ask whether to skip the automatic backup (default: no).
- Optionally add the preconfigured plugins.
- Detect the LDAP configuration.
- Check or add
CSRF_TRUSTED_ORIGINS. - Create the full pre-upgrade backup.
- Download the release archive from GitHub.
- Safely extract and verify the TAR archive.
- Carry over local files and directories.
- Stop the services.
- Switch the installation directory or symlink.
- Run
/opt/netbox/upgrade.sh. - Restart the services and verify their status.
- Keep the old installation as a fallback.
Download URL
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
netbox/netbox/configuration.py
If it is missing, the upgrade is aborted.
Optional files
netbox/netbox/ldap_config.py
local_requirements.txt
gunicorn.py
Optional directories
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:
netbox-topology-views
netbox-topology-views==4.2.1
netbox_topology_views>=4.0
Preconfigured plugins
On request the tool adds:
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:
ldap_config.pyis copied into the new installation.django-auth-ldapis ensured inlocal_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:
CSRF_TRUSTED_ORIGINS = [
"https://netbox.example.local",
]
During the upgrade, new origins can be entered comma-separated:
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:
https://netbox.example.local
http://192.168.1.50
https://netbox.example.local:8443
Invalid:
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:
# 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:
- re-activates the previous installation,
- 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:
- Restore menu →
1. Komplett-Restore. - Select the
netbox_pre_upgrade_v…backup. - The tool stops the services, restores installation files, database and media, runs
upgrade.shof the old version and restarts the services. - Check the logs.
Regular directory
The old installation is kept, e.g. at:
/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
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
{
"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
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_passin the script - configure
/root/.pgpass - configure local PostgreSQL authentication
dropdb or createdb fails
The configured user probably lacks the required privileges:
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
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
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
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_path": "/usr/bin/python3.12",
/usr/bin/python3.12 --version
Media files have wrong permissions
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:
- Check the service status.
- Check for running upgrade, pip or migration processes.
- Check the installation path and symlink target.
- Do not reset the database schema without a backup.
- 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.
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:
"backup_dir": "/srv/backups/netbox",
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
netboxandnetbox-rqare 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.shon restore, which requires access to PyPI (or your package mirror).
Recommended checks after an upgrade
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
# 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