PowerShell: Backing up a FortiGate via its API in PowerShell.

Before you continue please consider clicking on one of the horrible ads. I know they are a pain but they help me pay for the hosting of this site. It owes me a lot of money. Sob story over.

I took this on expecting it to be pretty horrible but in the end it turn out to be surprisingly easy to do.

The first thing you need to do is create a API user and for backups it will need some write permissions. I don't know which specific permission it needs to I just gave it all of them. You probably shouldn't do this.

The first thing we will do is create an new admin profile specifically for this new API users.

Log in as an admin and Under "System->Admin profiles:"

Create a new profile with read/write permissions to everything. You could just create the API user as a "SuperAdmin" at some point I plan to work out the exact permissions I need to make this work and change this group. Having it in its own group at this point will make that easier.

Now we need to make the API user. Under System->Administrators:

and create an API user and assign it to the profile we just created:

When we click OK you will be given the users API Token

Make a note of this, you will need it for the script.

Now that's all sorted we can get onto the PowerShell:

$ApiToken = "APITokenHere"
$BackupPath = "PathHere"

$EndPoint = "https://[fortigateIP]/api/v2/monitor/system/config/backup/?scope=global&access_token=$ApiTocken"
$header = @{ "Authorization" = "Bearer $ApiToken" }
$backup = Invoke-RestMethod -Method GET -Uri $EndPoint -Headers $Header 

New-Item $BackupPath
Set-Content $BackupPath $backup

And we are done. Easy.

In the research for this I found that some clever dick has actually written a whole PS module on managing fertigates which I decided was massive over kill for what I needed, however its fine work and worth sharing.

PowerFGT 0.6.1
PowerShell module to query the Fortigate API