Co-Authored-By: Claude Opus 5.5 <[email protected]>
NetBox Backup, Restore & Upgrade Tool
An interactive Python tool to back up, restore and upgrade a NetBox installation on Linux.
| Type | Interactive command-line tool (Python, standard library only) |
| Platform | Linux server running NetBox, with systemd |
| Python | >=3.8 |
| Repository | https://git.mrblake.cc/MrBlake/NetTransfare |
Important
This is not an official tool of the NetBox project. Test backup, restore and upgrade on a test instance first. Keep a current, externally stored backup before every upgrade.
Contents
- Features
- Requirements
- Installation
- Quick start
- Configuration
- Creating a backup
- Restoring a backup
- Upgrading NetBox
- Carried-over files and directories
- Plugins and LDAP
- CSRF trusted origins
- Rollback behaviour
- Backup layout
- Troubleshooting
- Security notes
- Known limitations
The tool's menus and prompts are in German; this README quotes them verbatim with an English translation.
Features
- Back up the PostgreSQL database
- Back up NetBox media files
- Store backups as a ZIP file
- Restore database and media files
- Download and install new NetBox releases
- Carry over configuration, LDAP settings, plugins, media files, reports and custom scripts
- Stop, start and check the NetBox services
- Keep the previous installation for a possible rollback
Requirements
Operating system
The tool targets a classic NetBox installation on Linux. The upgrade function requires:
- Linux or another POSIX system
systemd- root privileges
- write access to
/opt - internet access to GitHub
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 | Used for |
|---|---|
pg_dump |
Back up the PostgreSQL database |
pg_restore |
Restore a PostgreSQL dump |
dropdb |
Drop the existing target database on restore |
createdb |
Re-create the target database |
systemctl |
Stop and start the NetBox services |
cp |
Carry over configuration and local data on upgrade |
chown |
Set the owner of restored media files |
git |
Optional, to detect the installed NetBox version |
On Debian or Ubuntu, the PostgreSQL client programs are provided by the
postgresql-client package, for example.
NetBox directory layout
By default the tool expects NetBox under /opt/netbox, including:
/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 versioned directory.
NetBox services
The script uses these service names by default:
netbox
netbox-rq
For different unit names, adjust the NETBOX_SERVICES constant in the script.
Installation
Copy the script to /usr/local/sbin or another suitable directory:
sudo cp netbox_backup_restore_upgrade.py /usr/local/sbin/netbox-tool
sudo chmod 750 /usr/local/sbin/netbox-tool
sudo chown root:root /usr/local/sbin/netbox-tool
Then start it:
sudo /usr/local/sbin/netbox-tool
Or run it directly from the current folder:
chmod +x netbox_backup_restore_upgrade.py
sudo ./netbox_backup_restore_upgrade.py
Optionally check the Python syntax first:
python3 -m py_compile netbox_backup_restore_upgrade.py
Quick start
After starting, the main menu appears:
============================================================
NETBOX BACKUP, RESTORE & UPGRADE TOOL
============================================================
1. Backup erstellen
2. Backup wiederherstellen
3. NetBox upgraden
4. Einstellungen prüfen / anpassen
5. Beenden
(1 create backup, 2 restore backup, 3 upgrade NetBox, 4 check/adjust settings, 5 quit)
Recommended order before an upgrade:
- Check the settings.
- Create a full database and media backup.
- Copy the backup file to another system.
- Read the release notes of the target version.
- Check plugin compatibility.
- Start the upgrade.
- Check web interface, worker, plugins and logs.
Configuration
The defaults are 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": "",
}
| 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 archives | /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, set it:
"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 the PostgreSQL commands via the
PGPASSWORD environment variable.
For security, a PostgreSQL password file is often better suited:
/root/.pgpass, for example
localhost:5432:netbox:netbox:MY_PASSWORD
with permissions
chmod 600 /root/.pgpass
db_pass can then stay empty in the script.
Note
Changes made via Einstellungen prüfen / anpassen (check/adjust settings) apply only to the running process and are not saved to a file. For permanent changes, edit the
CONFIGblock in the script.
Creating a backup
Choose 1. Backup erstellen in the main menu.
Options
The tool asks whether to back up:
- the PostgreSQL database
- media files
For the database backup, the data of certain tables can be skipped.
Skipping the changelog
With this option, the contents of the extras_objectchange table are not
exported:
Changelog (extras_objectchange) auslassen? Spart viel Platz. (j/N)
(Skip changelog? Saves a lot of space. y/N.) The table structure stays in the dump; only its data is skipped. This can reduce the backup size considerably when change logging is extensive.
Skipping users
The contents of these tables are not exported:
auth_user
auth_group
users_token
Warning
Skipping users can lead to foreign-key problems or missing assignments on restore. Only use this option if the target system already has matching users or you know the consequences exactly.
Backup file
The file is named after this pattern:
netbox_backup_YYYYMMDD_HHMMSS.zip
for example /tmp/netbox_backup_20260720_143500.zip. On success, the tool
shows the full path.
Verifying the backup
ls -lh /tmp/netbox_backup_*.zip
unzip -l /tmp/netbox_backup_20260720_143500.zip
sha256sum /tmp/netbox_backup_20260720_143500.zip
Copy the backup to external storage:
scp /tmp/netbox_backup_20260720_143500.zip backupserver:/srv/backups/netbox/
Do not leave a backup only in /tmp; depending on the system configuration,
this directory may be cleared on reboot.
Restoring a backup
Choose 2. Backup wiederherstellen in the main menu.
Caution
Restoring overwrites the existing data of the target instance. The configured PostgreSQL database is dropped and re-created.
Steps
- Confirm the safety prompt.
- Enter the full path to the ZIP file.
- The archive is extracted into a temporary directory.
metadata.jsonis checked.- If included, the database is dropped and re-created.
- The PostgreSQL dump is imported.
- If included, media files are replaced.
upgrade.shis run.netboxandnetbox-rqare restarted.
Required database privileges
The configured database user needs sufficient privileges for the restore; in
particular, dropdb and createdb must work with this user. Check with:
sudo -u postgres psql -c "\du"
If the NetBox database user may not create databases, adapt the procedure or use an administrative PostgreSQL user.
Restore command
The dump is imported roughly like this:
pg_restore \
-h localhost \
-U netbox \
-d netbox \
--clean \
--no-owner \
netbox_database.dump
Messages from pg_restore are shown. Since PostgreSQL may return a non-zero
exit code even for individual warnings, the tool reports the restore as
finished and prints any notices. Check the database and the NetBox logs
afterwards.
Media files
Existing media files under /opt/netbox/netbox/media are replaced, and their
owner is then set to netbox:netbox.
Upgrading NetBox
Choose 3. NetBox upgraden in the main menu. The upgrade must be run as
root or with sudo.
Target version
The version can be entered with or without a leading v, for example 4.6.5
or v4.6.5. Only stable version numbers in the format X.Y.Z are accepted;
pre-releases such as 4.6.0-beta1 are rejected.
Version check
The tool tries to detect the installed NetBox version via:
- the name of the actual installation directory
- an exact Git tag
- the NetBox Python package in the existing virtual environment
- NetBox version files
The target version must be higher than the detected installed version. Downgrades are not automated. A detected major-version jump triggers an additional warning.
Upgrade steps
- Validate the target version.
- Check the existing NetBox installation.
- Ask for confirmation of backup and release notes.
- Optionally add the preconfigured plugins.
- Detect the LDAP configuration.
- Check or add
CSRF_TRUSTED_ORIGINS. - Download the release archive from GitHub.
- Safely extract and check the TAR archive.
- Carry over local files and directories.
- Stop the services.
- Switch installation directories or the symlink.
- Run
/opt/netbox/upgrade.sh. - Restart the services.
- Check the service status.
- Keep the old installation as a fallback.
Download address
The release is downloaded from:
https://github.com/netbox-community/netbox/archive/refs/tags/vX.Y.Z.tar.gz
The temporary archive is deleted after the upgrade.
Downtime
Download, extraction and preparation of the new installation happen before the services are stopped. Downtime only starts when switching to the new installation.
Services
netbox and netbox-rq are stopped before the switch. After a successful
upgrade.sh, both are restarted and checked with systemctl is-active.
Carried-over files and directories
On upgrade, these contents are copied from the existing installation into the new release.
Required file
netbox/netbox/configuration.py
If this file 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/
Contents are copied with cp -a, preserving permissions, timestamps and
symbolic links.
Customisations that are not carried over
Manual changes to files of the NetBox source code itself are not detected or merged — for example directly modified templates, Python files or static files outside the paths above. Implement such changes as a plugin, custom script or through a documented deployment process.
Plugins and LDAP
Existing requirements
An existing /opt/netbox/local_requirements.txt is carried over and its
entries are kept. The tool recognises package names and does not add a package
again if an unversioned or pinned entry already exists. These are treated as
the same package:
netbox-topology-views
netbox-topology-views==4.2.1
netbox_topology_views>=4.0
Preconfigured plugins
On request, the tool adds the entries of the DEFAULT_PLUGIN_REQUIREMENTS
constant, which ships with:
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
Adapt this list to your environment before use.
LDAP
If /opt/netbox/netbox/netbox/ldap_config.py exists in the current
installation, the tool:
- copies
ldap_config.pyinto the new installation, and - ensures
django-auth-ldapis inlocal_requirements.txt.
Plugin compatibility
The tool cannot reliably check whether a plugin supports the target NetBox
version; at the latest, this surfaces when upgrade.sh installs the
requirements. Before upgrading, check for every 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
after the restart.
CSRF trusted origins
The tool checks whether configuration.py contains a direct assignment:
CSRF_TRUSTED_ORIGINS = [
"https://netbox.example.com",
]
During the upgrade, new origins can be entered comma-separated:
https://netbox.example.com,http://192.0.2.50
Only origins with http:// or https://, a host name or IP address and an
optional port are accepted — no path, query or fragment.
Valid:
https://netbox.example.com
http://192.0.2.50
https://netbox.example.com:8443
Invalid:
netbox.example.com
https://netbox.example.com/netbox
https://netbox.example.com?test=1
When new origins are entered, the tool appends a new block to
configuration.py:
# Automatisch durch das NetBox-Upgrade-Tool gesetzt
CSRF_TRUSTED_ORIGINS = [
'https://netbox.example.com',
'http://192.0.2.50',
]
Note
If a direct assignment already exists and new values are entered as well, the file then contains two assignments; in Python the last one wins. Check the file after the upgrade and consolidate the setting if needed.
Dynamically imported or programmatically built CSRF settings may not be detected by this simple check. The tool warns in that case and asks for an additional confirmation.
Rollback behaviour
Rollback depends on when an error occurs.
Error before upgrade.sh starts
If the error happens after the directory switch but before upgrade.sh
starts, the tool automatically tries to re-activate the previous installation
and restart the NetBox services. At this point, no database migrations of the
new release have run.
Error after upgrade.sh starts
Once upgrade.sh has started, there is no automatic full rollback: database
migrations may already have run fully or partially, and switching only the
program directory back could combine an older NetBox with a newer database
schema.
A full rollback typically requires:
- Stop the services.
- Re-activate the previous installation.
- Restore the database from the backup made before the upgrade.
- Restore media files from the same backup if needed.
- Run the old installation's
upgrade.shor the necessary maintenance steps. - Start the services and check the logs.
Regular directory
If /opt/netbox is a regular directory, the old installation is moved, for
example, to /opt/netbox_old_20260720_143500. If that name exists, a running
number is appended.
Symlink installation
If /opt/netbox is a symlink, the new release is installed, for example, to
/opt/netbox-4.6.5, and the symlink is switched atomically. The previous
release directory is kept. The target directory must not exist yet; if
/opt/netbox-4.6.5 already exists, the tool aborts so no data is overwritten.
Backup layout
A full ZIP backup looks like this:
netbox_backup_YYYYMMDD_HHMMSS.zip
├── metadata.json
├── netbox_database.dump
└── media/
Depending on the chosen scope, netbox_database.dump or media/ may be
missing.
Metadata
Example metadata.json, used on restore to determine the included scope:
{
"version": "1.2",
"timestamp": "20260720_143500",
"source_db": "netbox",
"contains_db": true,
"contains_media": true,
"excluded_changelog": false,
"excluded_users": false
}
Safe extraction
The tool checks ZIP and TAR paths before extracting to prevent path traversal. TAR archives containing symbolic or hard links are rejected. Still, only use backups and release archives from trusted sources.
Troubleshooting
pg_dump: command not found
Install the PostgreSQL client:
sudo apt update
sudo apt install postgresql-client
With several PostgreSQL versions, use a client version matching the server.
PostgreSQL asks for a password
- set
db_passin the script, - configure
/root/.pgpass, or - set up local PostgreSQL authentication accordingly.
dropdb or createdb fails
The configured user probably lacks the required privileges. Check the PostgreSQL roles:
sudo -u postgres psql -c "\du"
Alternatively, adapt the restore so administrative database actions run with a separate PostgreSQL user.
Target version not found
NetBox-Release vX.Y.Z wurde auf GitHub nicht gefunden.
(Release not found on GitHub.) Check the spelling of the version, internet access, DNS resolution, proxy or firewall rules and whether the release exists.
Download fails behind a proxy
Python usually honours the standard variables:
export HTTPS_PROXY=http://proxy.example.com:3128
export HTTP_PROXY=http://proxy.example.com:3128
sudo -E ./netbox_backup_restore_upgrade.py
Mind the security implications of sudo -E.
configuration.py is missing
The tool expects /opt/netbox/netbox/netbox/configuration.py. Check
CONFIG["netbox_path"] and the actual NetBox directory layout.
Service does not start after the upgrade
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: an incompatible plugin, a wrong Python version, a missing system
library, errors in configuration.py or ldap_config.py, an incomplete
database migration, wrong file permissions or changed NetBox configuration
options.
upgrade.sh fails on a plugin
Temporarily comment out or remove the plugin in local_requirements.txt, if
that is acceptable for the migration in question. Then check the plugin
documentation and enter a compatible version. Always make sure a full backup
exists before making changes.
Wrong Python interpreter
Set it in the settings menu or permanently in the CONFIG block:
"python_path": "/usr/bin/python3.12",
Check the path:
ls -l /usr/bin/python3.12
/usr/bin/python3.12 --version
Media files have wrong permissions
ls -ld /opt/netbox/netbox/media
find /opt/netbox/netbox/media -maxdepth 2 -printf '%u:%g %p\n' | head
sudo chown -R netbox:netbox /opt/netbox/netbox/media
Upgrade interrupted with Ctrl+C
The global KeyboardInterrupt handler terminates the program. If upgrade.sh
had already started, do not assume an automatic rollback happened:
- Check the service status.
- Check the process list for running upgrade, pip or migration processes.
- Check the installation path and symlink target.
- Do not reset the database schema without a backup.
- Evaluate the logs and the upgrade output.
Security notes
Root privileges
Depending on file permissions, backup functions may work without root. Restore
and upgrade need elevated privileges for access to /opt/netbox,
systemctl, chown and the directory switch, so run the tool with sudo for
administrative tasks.
Passwords in the source code
A database password in the CONFIG block is readable by every user who can
read the script. Recommendations:
- provide the password via
.pgpasswhere possible - make the script readable by root only
- never commit scripts with credentials to public repositories
- store backups encrypted
sudo chown root:root /usr/local/sbin/netbox-tool
sudo chmod 700 /usr/local/sbin/netbox-tool
Protecting backups
A NetBox database backup can contain sensitive information such as user accounts, API tokens, device and site data, IP addresses, secrets from plugins, documents and images. Backups should be transferred and stored encrypted, be accessible only to authorised people and be deleted according to a defined retention plan.
/tmp as backup target
/tmp is a convenient 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, and one plugin requirement points to an external Git server. Before use, check trust in the source, reachability, the TLS certificate chain, the desired version or commit pinning, and internal software supply-chain policies. For reproducible installations, pin plugin versions or commits.
Known limitations
- Settings changed in the menu are not saved permanently.
- Plugin compatibility is not checked in advance.
- NetBox release notes are not read or interpreted automatically.
- Major upgrade paths only trigger a warning and are not fully validated.
- An automatic database rollback after a started migration is intentionally not implemented.
- PostgreSQL backup and restore use the same configured database user.
- The service names
netboxandnetbox-rqare hard-coded. - Additional services such as a separate housekeeping service, reverse proxy or monitoring agent are not restarted.
- Manual changes to the NetBox source code are not carried over.
- Newly entered CSRF origins are appended as an additional block instead of editing an existing one.
- No automatic HTTP health check of the NetBox web interface.
- No automatic backup rotation.
- Backups are not encrypted automatically.
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 interface, check that:
- login works
- the home page loads without errors
- objects and IPAM data are present
- images and documents are reachable
- custom scripts and reports are present
- background jobs are processed
- LDAP login works
- plugins are loaded
- API calls work
Check the installed version in the web interface or the local installation. Only remove the old installation and the backup once the new version has been verified and found stable.
Example of a safe upgrade
# 1. Start the tool
sudo /usr/local/sbin/netbox-tool
# 2. Choose menu item 1 and create a full backup
# 3. Store the backup externally
scp /srv/backups/netbox/netbox_backup_20260720_143500.zip \
backupserver:/srv/backups/netbox/
# 4. Save a checksum
sha256sum /srv/backups/netbox/netbox_backup_20260720_143500.zip \
> /srv/backups/netbox/netbox_backup_20260720_143500.zip.sha256
# 5. Start the tool again and choose menu item 3
sudo /usr/local/sbin/netbox-tool
# 6. After the upgrade, check services and logs
systemctl status netbox netbox-rq --no-pager
journalctl -u netbox -u netbox-rq --since "15 minutes ago" --no-pager
Disclaimer
Use at your own risk. An upgrade can fail because of incompatible plugins, changed configuration options, database migrations, missing dependencies or local customisations. 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