Skip to content

Instantly share code, notes, and snippets.

@hasanbasri1993
Forked from corny/unifi-backup.sh
Last active November 30, 2020 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasanbasri1993/78825202269c6bdb4d1aff2873ac9436 to your computer and use it in GitHub Desktop.
Save hasanbasri1993/78825202269c6bdb4d1aff2873ac9436 to your computer and use it in GitHub Desktop.
Improved backup script for Ubiquiti UniFi controller
#!/bin/bash -e
#
# Improved backup script for Ubiquiti UniFi controller
# original source: http://wiki.ubnt.com/UniFi#Automated_Backup
#
# must contain:
username=YOUR_USERNAME
password=YOUR_PASSWORD
baseurl=https://localhost:8443
output=/home/pi/backup
filename=`date +%Y%m%d%H%M`.unf
keep_days=1
# create output directory
mkdir -p $output
curl_cmd="curl --cookie /tmp/cookie --cookie-jar /tmp/cookie --insecure --fail"
# authenticate against unifi controller
if ! $curl_cmd --data '{"username": "'$username'","password": "'$password'","remember": true,"strict": true}' $baseurl/api/login > /dev/null; then
echo Login failed
exit 1
fi
# get Csrf-Token
value=`cat /tmp/cookie`
token="${value: -32}"
# ask controller to do a backup, response contains the path to the backup file
path=`$curl_cmd -H "X-Csrf-Token: $token" --data 'json={"cmd":"backup","days":"-1"}' $baseurl/api/s/default/cmd/backup | sed -n 's/.*\(\/dl.*unf\).*/\1/p'`
# download the backup to the destinated output file
$curl_cmd $baseurl$path -o $output/$filename
# logout
$curl_cmd $baseurl/logout
# delete outdated backups
find $output -ctime +$keep_days -type f -delete
echo Backup successful
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment