NetBox Backup, Restore & Upgrade Tool

🇩🇪 Deutsche Version

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
  2. Installation
  3. Quick start
  4. Configuration
  5. Creating a backup
  6. Restore menu
  7. Upgrading NetBox
  8. Files and directories carried over
  9. Plugins and LDAP
  10. CSRF trusted origins
  11. Rollback behaviour
  12. Backup layout
  13. Troubleshooting
  14. Security notes
  15. 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:

/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:

  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:

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 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:

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. 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.

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

  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

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:

  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:

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:

  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:

/opt/netbox_old_20260720_143500

If the name exists, a running number is appended.

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_pass in 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:

  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.

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 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).

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
S
Description
Netbox Transfare & In - Export Skript
Readme
267 KiB
0 Stars 1 Watchers 0 Forks
Languages
Python 100%