This article applies to PRTG Network Monitor 16.4.27 or later


I recently installed several Ubiquiti UniFi devices on my network. I have a UniFi Security Gateway (USG), two UniFi AP AC PRO wireless access points, and a UniFi Cloud Key. How can I monitor these devices with PRTG?


Monitoring Ubiqiti UniFi Devices with PRTG

We've put together an EXE/Script Advanced sensor that you can use to monitor general statistics and information of your Ubiquiti UniFi deployment, regarding especially the access points.


What the Sensor Monitors

The sensor shows you the following per-site statistics:

  • Response time from the controller's API
  • Number of Connected Clients (Total (Clients+Guests))
  • Number of Connected Guests
  • Number of Connected Access Points (UAPs in Connected status)
  • Number of Upgreadeable Access Points (UAPs in Connected status with upgradable flag set)

Requirements

  • PRTG Network Monitor 16.4.27 or later
  • The PRTG probe on which you want to deploy the sensor must be able to reach the UniFi controller on the "API" port (default is 8443).
  • The PRTG probe on which you want to deploy the sensor must run PowerShell version 3 or later.
  • The script was tested with the UniFi controller versions 5.3.8 ~ 6.0.43.
    Note: We cannot guarantee that it works with other UniFi controller versions.
  • Configure your PRTG probe to enable the execution of unsigned scripts/code. For further information refer to the Knowledge Base articles Guide for PowerShell based custom sensors and PowerShell 32-bit and 64 bit and execution policy.

Known Limitations

The sensor will not produce any alerts by default, unless it is unable to authenticate or contact the UniFi controller. Once the sensor is deployed, you're advised to set up limits in the channel's settings. For example, define a lower error limit for the number of connected access points. This way you are notified as soon as the number of connected access points is lower than expected. See also the Paessler website: How to set up notifications via the PRTG web interface.

Workaround for UDM Pro API

IMPORTANT: If you're using an Unifi Cloudkey you might have to apply this small workaround:

For some reason (according to ubntwiki.com) the API endpoints are slightly different in this variant of the Unifi Controller. For example on UCK-G2 (UniFi® CloudKey Gen2). While the script is compatible, it requires two little changes to work in this case:

  • The authentication URL in the script must be $controller/api/auth/login (instead of $controller/api/login)
  • The query URL in the script must be $controller/proxy/network/api/s/$site/stat/device/ (instead of $controller/api/s/$site/stat/device/)

With these two changes, monitoring should work like a charm even on these devices.

Sensor Creation and Usage

1. Copy the Custom Sensor Code below and save it as Custom Powershell Unifi Status.ps1 under the following path of the desired PRTG Probe:

C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML

2. Create a new device in PRTG with the address (IP or FQDN) of the UniFi Controller that you want to monitor.

3. Now, select Add Sensor. On the search field, type "Script Advanced" and then select the EXE/Script Advanced sensor from the result list.

4. On the Add Sensor to Device screen, enter the following:

4.1 The sensor's name and tags (optional)

4.2 Under Exe/Script, use the Drop-down to select Custom Powershell Unifi Status.ps1 from the list.

4.2 The parameters should be:

-server '%host' -port '8443' -site 'default' -username 'ctrllerUsername' -password 'ctrllerPassword'

You can omit -port and -site when working with the default. For non-default sites, use the site's "code": Instead of the site name you have to pick up the number of the site by checking the URL example:

Https:unifi.yourdomain.com:8443/manage/site/3kh0qlq5/devices/1/50

In this case 3kh0qlq5 is the ID which you should use as a site name in this script


4.3 Unless required for other reasons, leave the default Environment and Security Context and Mutex Name.

4.4 Reduce the Timeout to 30 seconds, the query shouldn't take this long.

4.5 The EXE Result should only be enabled if you need to troubleshoot the sensor's execution.

4.6 Click Continue to deploy the sensor.

5. The sensor should display channels and values after one scanning interval. Once this happened, you can start adjusting the channel limits to your requirements (optional).

The Script

This is the sensor's PowerShell code:

# Monitor the Status of AP's on Unfi Controller in PRTG v0.8 27/06/2017
# Published Here: https://kb.paessler.com/en/topic/71263
#
# Parameters in PRTG are: Controller's URI, Port, Site, Username and Password. Example without placeholders:
# -server 'unifi.domain.tld' -port '8443' -site 'default' -username 'admin' -password 'somepassword'
#
# -server '%host' -port '8443' -site 'default' -username '%windowsuser' -password '%windowspassword'
# This second option requires the device's address in PRTG to be the controller's address, the credentials for windows devices
# must also match the log-in/password from the controller. This way you don't leave the password exposed in the sensor's settings.
#
# It's recommended to use larger scanning intervals for exe/xml scripts. Please also mind the 50 exe/script sensor's recommendation per probe.
# The sensor will not generate alerts by default, after creating your sensor, define limits accordingly.
# This sensor is to be considered experimental. The Ubnt's API documentation isn't completely disclosed.
#
# Source(s):
# http://community.ubnt.com/t5/UniFi-Wireless/little-php-class-for-unifi-api/m-p/603051
# https://github.com/fbagnol/class.unifi.php
# https://www.ubnt.com/downloads/unifi/5.3.8/unifi_sh_api
# https://github.com/malle-pietje/UniFi-API-browser/blob/master/phpapi/class.unifi.php
# https://ubntwiki.com/products/software/unifi-controller/api

param(
[string]$server = 'unifi.domain.com',
[string]$port = '8443',
[string]$site = 'default',
[string]$username = 'admin',
[string]$password = '123456',
[switch]$debug = $false
)

#Ignore SSL Errors
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

#Define supported Protocols
[System.Net.ServicePointManager]::SecurityProtocol = @("Tls12","Tls11","Tls","Ssl3")


# Confirm Powershell Version.
if ($PSVersionTable.PSVersion.Major -lt 3) {
Write-Output "<prtg>"
Write-Output "<error>1</error>"
Write-Output "<text>Powershell Version is $($PSVersionTable.PSVersion.Major) Requires at least 3. </text>"
Write-Output "</prtg>"
Exit
}

# Create $controller and $credential using multiple variables/parameters.
[string]$controller = "https://$($server):$($port)"
[string]$credential = "`{`"username`":`"$username`",`"password`":`"$password`"`}"

# Start debug timer
$queryMeasurement = [System.Diagnostics.Stopwatch]::StartNew()

# Perform the authentication and store the token to myWebSession
try {
$null = Invoke-Restmethod -Uri "$controller/api/login" -method post -body $credential -ContentType "application/json; charset=utf-8" -SessionVariable myWebSession
}catch{
Write-Output "<prtg>"
Write-Output "<error>1</error>"
Write-Output "<text>Authentication Failed: $($_.Exception.Message)</text>"
Write-Output "</prtg>"
Exit
}

#Query API providing token from first query.
try {
$jsonresultat = Invoke-Restmethod -Uri "$controller/api/s/$site/stat/device/" -WebSession $myWebSession
}catch{
Write-Output "<prtg>"
Write-Output "<error>1</error>"
Write-Output "<text>API Query Failed: $($_.Exception.Message)</text>"
Write-Output "</prtg>"
Exit
}

# Load File from Debug Log
# $jsonresultatFile = Get-Content '.\unifi_sensor2017-15-02-05-42-24_log.json'
# $jsonresultat = $jsonresultatFile | ConvertFrom-Json

# Stop debug timer
$queryMeasurement.Stop()


# Iterate jsonresultat and count the number of AP's.
# $_.state -eq "1" = Connected
# $_.type -like "uap" = Access Point ?

$apCount = 0
Foreach ($entry in ($jsonresultat.data | where-object { $_.state -eq "1" -and $_.type -like "uap"})){
$apCount ++
}

$apUpgradeable = 0
Foreach ($entry in ($jsonresultat.data | where-object { $_.state -eq "1" -and $_.type -like "uap" -and $_.upgradable -eq "true"})){
$apUpgradeable ++
}

$userCount = 0
Foreach ($entry in ($jsonresultat.data | where-object { $_.type -like "uap"})){
$userCount += $entry.'num_sta'
}

$guestCount = 0
Foreach ($entry in ($jsonresultat.data | where-object { $_.type -like "uap"})){
$guestCount += $entry.'guest-num_sta'
}

#Write Results

write-host "<prtg>"

Write-Host "<result>"
Write-Host "<channel>Access Points Connected</channel>"
Write-Host "<value>$($apCount)</value>"
Write-Host "</result>"

Write-Host "<result>"
Write-Host "<channel>Access Points Upgradeable</channel>"
Write-Host "<value>$($apUpgradeable)</value>"
Write-Host "</result>"

Write-Host "<result>"
Write-Host "<channel>Clients (Total)</channel>"
Write-Host "<value>$($userCount)</value>"
Write-Host "</result>"

Write-Host "<result>"
Write-Host "<channel>Guests</channel>"
Write-Host "<value>$($guestCount)</value>"
Write-Host "</result>"

Write-Host "<result>"
Write-Host "<channel>Response Time</channel>"
Write-Host "<value>$($queryMeasurement.ElapsedMilliseconds)</value>"
Write-Host "<CustomUnit>msecs</CustomUnit>"
Write-Host "</result>"

write-host "</prtg>"

# Write JSON file to disk when -debug is set. For troubleshooting only.
if ($debug){
[string]$logPath = ((Get-ItemProperty -Path "hklm:SOFTWARE\Wow6432Node\Paessler\PRTG Network Monitor\Server\Core" -Name "Datapath").DataPath) + "Logs (Sensors)\"
$timeStamp = (Get-Date -format yyyy-dd-MM-hh-mm-ss)

$json = $jsonresultat | ConvertTo-Json
$json | Out-File $logPath"unifi_sensor$($timeStamp)_log.json"
}

Result

The resulting sensors (after setting limits) will look like the following (Sensor v0.4):

Sensor Overview

The sensor's settings will look like this:

Sensor Settings

Troubleshooting

Got any issues?

  • Check your Powershell version. Just type $PSVersionTable in a PowerShell prompt.
  • Make sure that the execution of scripts is allowed on the PRTG Probe where you've deployed the sensor.
  • If you're using a Cloud Key you might need to apply the instructions described in the "Workaround for UDM Pro API" section, otherwise all values might be "0".
  • Double check that the parameters are correct and that the credentials are valid.
  • Make sure that the remote probe can reach the UniFi controller at the required port. A proxy may not work here.
  • You can append the -debug parameter, the script will then write the whole JSON-formatted content to a file named unifi_sensor...json under Logs (Sensors) in PRTG's Data Path. This should be disabled when debugging is complete as it will endlessly create new files.
  • For any other troubles: Don't hesitate to contact us by replying to this post or by contacting us via a support ticket. Please also link this Knowledge Base post.

Version History

0.12017/01-Initial Release
0.42017/01-Now Ignores SSL Certificate issues
0.52017/02-Includes a channel for "Access Points Upgradeable"
0.72017/02-Includes a command line switch for debugging on the JSON response
-Only polls guests from uap devices(improved filter)
0.82017/06-SSL/TLS compatibility improved

Remarks

  • Please understand that we cannot provide in-depth technical support for custom sensors nor can we guarantee that the above described sensors will work on your systems. You use all components at your own risk.
  • Feel free to further modify this script to monitor other properties, feel free to share it (free of charge) as well.
  • msxfaq.de provides a "fork" of the original script on their website. German only: PRTG mit Ubiquiti WLAN Access Points
  • There is also a fork of this script/sensor by TS-Steff to monitor Unifi Switches and Gateways as well. You can find it here.

Best Regards,
Luciano Lingnau [Paessler Support]

More



Disclaimer:
The information in the Paessler Knowledge Base comes without warranty of any kind. Use at your own risk. Before applying any instructions please exercise proper system administrator housekeeping. You must make sure that a proper backup of all your data is available.