Sample bash script for backups using the API

Started by bartjsmit, December 23, 2019, 08:48:30 PM

Previous topic - Next topic
This is tested on CentOS but should be easily portable to other unix systems. Prerequisites are an OPNsense admin user with an API key, which does not require interactive login or a known password. It does not produce output when successful, so when called from cron it will email root with errors. Binaries needed are date, curl, gzip and find.

Bart...

#!/usr/bin/bash

# Change API key and secret, number of days to keep backups, the path to your backups and the hostname for your firewall

key="api key for backup user"
secret="api secret for backup user"
daystokeep=3
destination="/path/to/firewall/backups"
fwhost="firewall.fqdn"

date=$(date +%Y-%m-%d)

result=$(/usr/bin/curl -I -s -k -u "$key":"$secret" https://$fwhost/api/backup/backup/download | head -1)

if [[ $result != *"200"* ]]; then
   echo "Result of the HTTP request is $result"
   exit 1
fi

/usr/bin/curl -s -k -u "$key":"$secret" https://$fwhost/api/backup/backup/download > $date.xml

error=$?

if [ $error -gt 0 ]; then
   echo "Curl returned error number $error"
   exit 1
fi

/usr/bin/gzip $date.xml

mv $date.xml.gz $destination
/usr/bin/find $destination/* -mtime +$daystokeep -exec rm {} \;

 Hi,

I'm trying to back up my OPNSense instance using the REST API but when trying:

curl -s -k -u "$key":"$secret" https://$FW/api/backup/backup/download

it returns:

{"message":"controller OPNsense\\Core\\Api\\IndexController not found","status":400}

As a test, I tried

curl -k -u "$key":"$secret"  https://$FW/api/core/firmware/status

and it works as expected

Currently running on OPNsense 20.1.4-amd64

Any idea what might wrong?

Thanks!

You may be missing the os-backup-api plugin


To help this come up in search results, the name of the plugin is os-api-backup, not os-backup-api.

I took your script as an example and created a version which also encrypts the backups using GPG.

You can find the script here:
https://codeberg.org/SWEETGOOD/andersgood-opnsense-scripts/src/branch/main/backup-opnsense-via-api.sh

I also wrote a short blogpost in German with some explanations:
https://andersgood.de/kurz-notiert/opnsense-per-api-verschluesseltes-backup-der-konfiguration-anlegen

Thanks to the TS for your work!

Thank you for the script
I just realised that the path changed while backup plugin got incorporated