Skip to content

Instantly share code, notes, and snippets.

@corny
Last active November 14, 2024 18:51
Show Gist options
  • Save corny/3cf7af0f6cb7a00adeb3 to your computer and use it in GitHub Desktop.
Save corny/3cf7af0f6cb7a00adeb3 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=<username>
# password=<password>
source ~/.unifi-backup
baseurl=https://localhost:8443
output=/root/backups/unifi
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 --silent --fail"
# authenticate against unifi controller
if ! $curl_cmd --data '{"username":"'$username'","password":"'$password'"}' $baseurl/api/login > /dev/null; then
echo Login failed
exit 1
fi
# ask controller to do a backup, response contains the path to the backup file
path=`$curl_cmd --data 'json={"cmd":"backup","days":"-1"}' $baseurl/api/s/default/cmd/system | 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
@Pestage
Copy link

Pestage commented Jan 15, 2020

I don't understand, for me it's an html file or no download. Can you tell me how you test please ? I miss something I think. Thanks.

@MadddinTribleD
Copy link

MadddinTribleD commented Jan 16, 2020

  • installed powershell V6 (V6 adds -SkipCertificateCheck that i had to use because i dont have setup certs for my controller)
  • open powershell
  • set stuff like $BaseURI and $Username to my values
  • execute command by command

@staze
Copy link

staze commented Jan 18, 2020

will keep working on it, but right now, this just produces a 0KB backup from my UDMP when run from a linux machine. Clearly something isn't working. =/ I did modify endpoint as mentioned in this discussion.

@ChrisPF123
Copy link

will keep working on it, but right now, this just produces a 0KB backup from my UDMP when run from a linux machine. Clearly something isn't working. =/ I did modify endpoint as mentioned in this discussion.

I had the same problem on one of my controllers. Problem is that the user you are using to connect must be a Super Administrator.
I had the user set to just Administrator and i got 0Kb files.

@peschmae
Copy link

Careful!

This script can result in deleting a lot of unwanted files!

# delete outdated backups
find $output -ctime +$keep_days -type f -delete

should be ammended with

# delete outdated backups
find $output -ctime +$keep_days -type f -delete -iname "*.unf"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment