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, has anyone developed a sensor or script yet?
Can I monitor Ubiquiti UniFi network devices with PRTG?
Votes:
1
Best Answer
Votes:
4
This article applies to PRTG Network Monitor 16.4.27 or later
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 (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" as pointed out here by wimkoopman.
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):
The sensor's settings will look like this:
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.1 | 2017/01 | -Initial Release |
0.4 | 2017/01 | -Now Ignores SSL Certificate issues |
0.5 | 2017/02 | -Includes a channel for "Access Points Upgradeable" |
0.7 | 2017/02 | -Includes a command line switch for debugging on the JSON response -Only polls guests from uap devices(improved filter) |
0.8 | 2017/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
Created on Jan 10, 2017 6:52:00 AM by
Luciano Lingnau [Paessler]
Last change on Mar 9, 2022 1:05:55 PM by
Luciano Lingnau [Paessler]
79 Replies
Votes:
0
Update: Please refer to Custom Script for Unifi
Hello KAL,
thank you for your KB-Post.
We haven't experimented with Ubiquity's devices until now, from support experience we know that some device families (Airmax, Airfiber) implement SNMP (V1, rather limited) through proprietary or trough Mikrotik's MIB, but at this time there's no definitive answer we can provide on the subject for the UniFi family of devices.
The UniFi Controller offers an HTTP API that can be used to query statistics, for PRTG integration this would mean a custom exe/script sensors or multiple HTTP XML/REST Value Sensor(if compatible).
Should these devices be compatible with SNMP, please check:
- KB: Can't find a sensor for my device in PRTG but I believe it supports SNMP. How to proceed?
- KB: What can I monitor with the SNMP Custom Table Sensor?
I'll leave your inquiry open should someone else with more experience on these devices be able to contribute as well.
Best Regards,
Luciano Lingnau [Paessler Support]
Created on Sep 16, 2016 12:13:48 PM by
Luciano Lingnau [Paessler]
Last change on Jan 10, 2017 8:20:52 AM by
Luciano Lingnau [Paessler]
Votes:
4
This article applies to PRTG Network Monitor 16.4.27 or later
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 (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" as pointed out here by wimkoopman.
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):
The sensor's settings will look like this:
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.1 | 2017/01 | -Initial Release |
0.4 | 2017/01 | -Now Ignores SSL Certificate issues |
0.5 | 2017/02 | -Includes a channel for "Access Points Upgradeable" |
0.7 | 2017/02 | -Includes a command line switch for debugging on the JSON response -Only polls guests from uap devices(improved filter) |
0.8 | 2017/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
Created on Jan 10, 2017 6:52:00 AM by
Luciano Lingnau [Paessler]
Last change on Mar 9, 2022 1:05:55 PM by
Luciano Lingnau [Paessler]
Votes:
1
Hi Great sensor !!!! It works fine on the default site, however on any other site it returns error 401 Niet gemachtigd (Not Authorized) From the controller point of view I authenticated with the main account, which should have no restrictions Please let me know if you have any suggestions
Update: It also works on other sites, but 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
Update 2: Additional question:
- Can you easily add information like 2G clients 5G Clients RX TX CH. Util 2G CH. Util 5G Would be highly appreciated !!!
Created on Jan 16, 2017 7:27:47 AM
Last change on Jan 16, 2017 8:30:54 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hello wimkoopman,
thank you very much for your feedback and input.
I've "merged" all your replies together. :)
Regarding your inquiry, yes, that should be possible with minor modifications. As a general rule, everything that's available in the web-interface (properties, counters) is also available in the API.
I advise you to copy/paste this code into Powershell's ISE, you can then run the code once to get all variables assigned with values. Then, just run (using Run Selection) the following command/variable: $jsonresultat.
This will print-out the whole content of the variable, which is a huge chunk of JSON-encoded data. There are tens if not hundreds of properties available, feel free to modify the script (or add/remove logic and channels) to fit exactly your requirements. There are also links in the script to the available documentation provided by unifi, it provides hints to what's available/possible.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
This looks great!
Im trying to get it work, but I dont know if im doing something crazy. I get an error when creating the sensor
XML: The returned XML does not match the expected schema. (code: PE233) -- JSON: The returned JSON does not match the expected structure (Invalid JSON.). (code: PE231) |
Anyone have any guess what this could be?
The controller is ver 5.2.9 PRTG is 17.1.28.1341
Created on Mar 9, 2017 10:10:17 PM
Last change on Mar 10, 2017 7:54:04 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hello there Bosse, please beware that I haven't tested the script with version 5.2.9, so I can't guarantee that it ever worked. However, I don't see why it shouldn't..
Please try something else: Instead of deploying the sensor in PRTG, open up the 32-bit powershell shell (Windows Powershell x86), navigate to the path of the script and run it from there, using the same parameters.
Windows PowerShell Copyright (C) 2015 Microsoft Corporation. All rights reserved. PS C:\> cd '.\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML' PS & '.\Custom Powershell Unifi Status.ps1' -server "unifi.domain.tld" -port "8443" -site "default" -username "user" -password "somepassword"
What's the outcome? This may provide us further details about what's going wrong.
Please also make sure that you're running a supported powershell version on the server and that you've followed the Guide for PowerShell based custom sensors
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
Hello Luciano,
Thanks for your very helpfull tips. I did as you wrote. I tested the script directly in PS and noticed some issues (only my fault). After some trial and error it worked perfectly. The sensor is now up and running!
Thanks alot!
Votes:
0
Looks great ! However, I'm stuck with PS v2 on some of my servers (SBS2008). Has anyone rewritten this PS script for PS 2 ?
Votes:
0
Hello Dirk,
thank you for your reply.
I'm not aware of any Powershell V2 compatible version, you could try converting it. For instance:
I'm not sure if any other cmdlets will also required adjustments. Keep in mind however that you could employ a remote probe in PRTG, this would allow you to run the script somewhere else (on a different system). Or even, do an Invoke-Command and run the script on a different system that has a newer powershell version.
I'll leave your reply published in case anyone else has input, but I'm not working on any PS2.0 compatible version at the moment.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
updated my Unifi Controller to 5.6.x unfortunately the PS script has stopped working. any ideas?
Votes:
0
Dear crazypete00
Please clarify what "stopped working" means in this case.
Votes:
0
I tried this now, and get this message in PRTG:
XML: The returned XML does not match the expected schema. (code: PE233) -- JSON: The returned JSON does not match the expected structure (Invalid JSON.). (code: PE231)
Votes:
0
Hello @Morbus,
thank you for your reply.
I encourage you to run the script from the command-line to check whenever it works. But keep in mind that you need to include the correct parameters. You can also include -debug in the parameters to write a log file. Please refer to the "Troubleshooting" section in the main article.
Hello @crazypete00. Please note that the latest stable unifi release at the time of this writing is 5.4.16 - I can confirm that the sensor works with that version but haven't tried the beta version yet. If you get me credentials and a controller to connect to I can take a look into why it doesn't work.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
Hello everyone,
I am trying to add Unify AP into PRTG, I am getting an error from PRTG that user is not authorizerd. Can you please tell me if this can be related to SW that we are running on WLC - 3.2.10 Power shell is 4, and account that I am using has role as admin.
Thank you, Best regards, Pavel Kedron
Votes:
0
Hello Pavel,
thank you for your post/reply.
I've never tested the script against a 3.2.10 controller. The API's could greatly differ and I'm unable to confirm that it would work. You may want to consider upgrading/deploying version 5.x instead.
Other than that "user is not authorizerd" sounds like an authentication issue. Make sure you're providing valid credentials to the script. Otherwise, please let me know the complete result/error. If you have a proxy in place it could also be denying the HTTP connection to the controller.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
Hello,
This is a good Sensor. I run this on different devices. But since last night I have on one of them an Error. In the night nobody changed some settings. But nearly 0:00 the sensor stopped working. Error message is :
<prtg> <error>1</error> <text>Authentication Failed: The underlying connection was closed: An unexpected error occurred on a receive.</text> </prtg>
I tried in Power Shell ISE same Error and with –Debug
But could not find a Debug File.
Shuld the Debug File not be on the Core Server \PRTG_DB\Logs (Sensors)?
Created on Sep 13, 2017 8:13:00 AM
Last change on Sep 13, 2017 8:36:52 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hello there,
thank you for your reply.
Please double check that you're using the latest version (0.8) of the ps1 file, published on 27/06/2017. As for the message:
An unexpected error occurred on a receive. |
This could be related to the SSL cyphers. Please note that the script is specially configured to accept/work with the following:
[System.Net.ServicePointManager]::SecurityProtocol = @("Tls12","Tls11","Tls","Ssl3")
Are you using any different protocol or version? You could change this setting (directly in the script) for additional testing. Is the Unifi controller that is being polled up-to-date? Was the Powershell version on the probe perhaps updated/downgraded?
The exception is thrown by the Invoke-Restmethod, so you could also search for generic documentation about this error: powershell "An unexpected error occurred on a receive"
Lastly, regarding the -debug option. It will only work if the sensor is actually able to perform the API call. Since the authentication is failing, the sensor doesn't even connect (and the debug isn't written).
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
Excellent - worked like a charm! Many thanks for this!
Votes:
0
Thank you for the information. I seem to be having the issue where I am receiving the error:
XML: The returned XML does not match the expected schema. (code: PE233) -- JSON: The returned JSON does not match the expected structure (Invalid JSON.). (code: PE231)
within the console.
If I run the script from Powershell, it seems to run fine:
PS C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML> C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML\Custom Powershell Unifi Status.ps1 <prtg> <result> <channel>Access Points Connected</channel> <value>4</value> </result> <result> <channel>Access Points Upgradeable</channel> <value>0</value> </result> <result> <channel>Clients (Total)</channel> <value>12</value> </result> <result> <channel>Guests</channel> <value>11</value> </result> <result> <channel>Response Time</channel> <value>936</value> <CustomUnit>msecs</CustomUnit> </result> </prtg>
I'm not sure what is going on here or what I'm doing wrong. I have the sensor setup under the Windows server that I have the Unifi Controller on. I have the sensor parameters setup with:
-server '%host' -port '8443' -site 'default' -username 'admin' -password 'mypassword' |
I also tried the german extended script, but could not get that to work either.
Any help is appreciated.
PRTG
PRTG Enterprise Console | v17.4.35.3441 |
---|
Powershell:
PSVersion | 3.0 |
---|---|
WSManStackVersion | 3.0 |
SerializationVersion | 1.1.0.1 |
CLRVersion | 4.0.30319.36366 |
BuildVersion | 6.2.9200.22199 |
PSCompatibleVersions | {1.0, 2.0, 3.0} |
PSRemotingProtocolVersion | 2.2 |
Created on Nov 29, 2017 6:59:26 PM
Last change on Nov 30, 2017 6:58:18 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hello @stu68,
thank you for your reply.
The output from the command-line confirms that the sensor is working and so is the authentication/credentials. Now we need to find out what causes the XML code produced by PRTG to not work (what leads to PE231).
Within the Sensor's settings it is possible to set the "EXE Result" to "Write EXE result to disk". Once configured to do so a resulting Text File (Filename: 'Result of Sensor [ID].txt') will be stored under the Logs (Sensors) directory on the next scan of the sensor.
This folder's path is by default "C:\ProgramData\Paessler\PRTG Network Monitor" of the probe where the sensor is monitored.
Please have a look at the generated files, it may contain the description for a powershell error, for example telling you that the executionpolicy doesn't allow the sensor to run the file/script. In this case please have a look here:
If you're not able to spot anything wrong with the logs of the sensor, please share these so that we can have a look.
Best Regards,
Luciano Lingnau [Paessler Support]
Created on Nov 30, 2017 9:50:46 AM by
Luciano Lingnau [Paessler]
Last change on Nov 30, 2017 9:50:56 AM by
Luciano Lingnau [Paessler]
Votes:
1
Thank you Luciano. It ended up being the 32 bit Powershell restrictions. Once I did that it worked fine.
Votes:
0
Hello,
i have same problem : XML:
The returned XML does not match the expected schema. (code: PE233) -- JSON: The returned JSON does not match the expected structure (Invalid JSON.). (code: PE231) |
Powershel | l x64 and x86 Urestricted |
---|---|
PRTG | 18.1.36.3728 |
Ubiquiti ctrl | 5.6.29 |
Idea ?
Very Thanks
Created on Jan 20, 2018 10:53:54 AM
Last change on Jan 23, 2018 7:01:58 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hello @yvan_rossier,
thank you for your reply.
What happens if you run the script manually/interactively? (with the appropriate parameters)
Alternatively, you could configure/enable the "Write EXE result to disk" to find out what the actual output is (that leads to the PE231 error).
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
I recently updated Unifi to a new version (5.6.29) which is beyond the the firmware listed above. I now get the error "Authentication Failed: The request was aborted: Could not create SSL/TLS secure channel." when ran from PS.
Would any one have any suggestions on what might cause that error? I would really like to get this sorted as I find it is a very useful sensor.
Votes:
0
Hello BF,
thank you for your reply.
I have not validated the sensor against the version above because I didn't get a chance to update yet, but will update the document/page as soon as I've updated to test.
However, the following error is produced by powershell, not by "my script" (actually) :
The request was aborted: Could not create SSL/TLS secure channel. |
So it appears as if for some reason powershell doesn't like the certificate os ciphers supported by your instance. The script is supposed to work with TLS1.2, TLS1.2, TLS and SSL3.0. The sensor is also supposed to ignore certificate errors.
Unfortunately that's all I can tell you for now, but will update the document as soon as I've updated my test controller.
Best Regards,
Luciano Lingnau [Paessler Support]
Created on Feb 1, 2018 1:47:23 PM by
Luciano Lingnau [Paessler]
Last change on Feb 2, 2018 7:18:18 AM by
Luciano Lingnau [Paessler]
Votes:
0
Thanks for the reply Luciano.
Your reply lead me to resolve my problem. I had not updated my script to the latest version. It now connects fine.
Thanks for your assistance.
Votes:
0
Hoorray BF,
thank you for your reply and happy to hear it worked out.
All settled then. Have a nice weekend!
Cheers,
Luciano Lingnau [Paessler Support]
Votes:
0
Morning,
THIS SCRIPT IS AWSOME!
Thanks for creating and sharing it. Any chance it could also include some data like Top AP (user/bandwidth), or throughput in last 24 hours. Details like you see on the main Ubiquiti statistic page?
Cheers.
Votes:
0
Morning,
FEEDBACK IS AWESOME! :)
You're more than welcome, I'm happy it was useful to you. The problem with this sort of "top" metric is that PRTG doesn't really have a way to display it in PRTG, channels are too static for this sort of information and I'm not able to display custom data in a toplist at the present time.
Under remarks, there is a link to msxfaq.de: PRTG mit Ubiquiti WLAN Access Points, this is a "fork" of my script that includes per-access point data, in case that helps you in any way (but it requires one sensor per access point, so it may only be useful/applicable up to a deployment size).
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
Is there a way to get more information via PS from the USG?
Votes:
0
Hello Peter,
thank you for your reply.
Haven't had a chance to try that yet, but if the information is available on the Unifi Controller over the API, then most likely it could be polled using a similar script as the one above.
What sort of metrics/values/readings from the USG are you looking for?
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
I have upgraded the controller from 5.4 to 5.7 and now I too am getting "Authentication Failed: The request was aborted: Could not create SSL/TLS secure channel"
I get this if I run the Powershell script from the PRTG server, or directly on the Windows server running the Unifi controller software.
Any suggestions?
Votes:
0
Hello miyo360,
thank you for your reply.
Please double check that you are indeed using the latest available version of the powershell code, the original version of the sensor/script didn't correctly handle some cyphers, as I've mentioned here.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
hello, you have installed Java x64? (http://javadl.oracle.com/webapps/download/AutoDL?BundleId=230542_2f38c3b165be4555a1fa6e98c45e0808)
Votes:
0
@yvan_rossier,
thank you for your contribution.
The Custom sensor runs in powershell and interacts with the Web-Interface/API of the controller directly, no JAVA is required for the sensor to work.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
@Luciano Lingnau Thanks for the response. I googled the error and tried the suggestion here: https://stackoverflow.com/questions/41618766/powershell-invoke-webrequest-fails-with-ssl-tls-secure-channel
I then fixed the script error by...
commenting out your line:
#[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
adding this line:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
The sensor now works
Created on Apr 3, 2018 9:55:01 AM
Last change on Apr 3, 2018 7:08:12 PM by
Dariusz Gorka [Paessler Support]
Votes:
0
Hello miyo360,
thank you for your reply and feedback.
It's interesting to hear that this worked. Because basically, the first line (see below) should essentially tell the script to ignore any certificate errors (Self signed certificates for example). The second line should tell Powershell to accept all of the Security Protocols (("Tls12","Tls11","Tls","Ssl3")). But if changing that to allow TLS1.2 only worked for you, I'm happy with that. :)
#Ignore SSL Errors [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} #Define supported Protocols [System.Net.ServicePointManager]::SecurityProtocol = @("Tls12","Tls11","Tls","Ssl3")
Cheers!
Luciano Lingnau [Paessler Support]
Created on Apr 16, 2018 7:16:29 AM by
Luciano Lingnau [Paessler]
Last change on Jun 11, 2018 11:45:56 AM by
Luciano Lingnau [Paessler]
Votes:
0
This works great. But is there similar sensors for the switches and gateways from Unifi?
Votes:
0
Hello Artius,
thank you for your reply.
Regarding your inquiry:
This works great. But is there similar sensors for the switches and gateways from Unifi? |
There are currently no plans for this. But should be possible with minor modifications to the script.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
Running Controller Version 5.6.37 (Version: atag_5.6.37_10328) I receive an error:
"API Query Failed: The remote server returned an error: (401) Unauthorized." |
Authentication itself is working good. Any hints on this issue?
- Thomas
Created on Jul 22, 2018 10:24:40 AM
Last change on Jul 23, 2018 7:34:18 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hello Thomas,
thank you for your inquiry.
Please try and run the script from the cmd, do you get the same output?
Essentially, the following catch is "tripping":
# 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 }
The The remote server returned an error: (401) Unauthorized. error actually comes from the controller itself.
Perhaps the account isn't allowed to use the API? Or the password and site don't match? (If you don't specify a site, it will use the default. If you specify a different one, it will use the different one. Double-check that the user has access to the queried site.
If the above doesn't explain the issue, perhaps your account name or password contains ' and this is escaping the password and messing the script? You could try with a alphanumerical account and password (no special characters).
Version 5.6.37 should definitively work.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
Controller Version is 5.8.24 and script is version (0.8) published on 27/06/2017.
I got Unauthorized Access. I have no problem to access the controller by using chrome so username and password should be correct and password no ' and special char.
Any help appreciated.
Votes:
0
Hello ryanpat,
thank you for your reply.
Please refer to my previous explanation about this error:
If you're still unable to explain the behavior, please contact us and reference case number PAE1068262. But you will need to provide us temporary credentials to test the script/sensor with your instance for us to be able to investigate this further.
Best Regards,
Luciano Lingnau [Paessler Support]
Votes:
0
I am having the same error as @yvan_rossier, whenever there is NOT also a sensor of type "HTTP Push Data Advanced" running on the same device, using port 5050. I can't seem to figure out why that is needed. I tried this version and the German "fork" of it.
Votes:
0
Is this the first custom PowerShell script for this PRTG installation? If so, please review our guide for PowerShell based custom Sensors, especially step 1.
PRTG Scheduler |
PRTGapi |
Feature Requests |
WMI Issues |
SNMP Issues
Kind regards,
Stephan Linke, Tech Support Team
Votes:
1
As I was one of the impatient people about to post asking for help with the XML/JSON error below, I thought I'd better contribute back with a positive response instead.
The returned XML does not match the expected schema. (code: PE233) -- JSON: The returned JSON does not match the expected structure (Invalid JSON.). (code: PE231)
I had turned on -debug and set the Exe result to write to file on error as proposed by Paessler representatives several times on this thread, but nothing was happening. (With it set to ...on error... it was giving a blank file; I had to set it to ...every time... to get the actual PS error appearing)
I had also tested in Powershell and it was generating the expected results.
I had also set the execution policy as stated in the "Guide for Powershell based sensors".... or so I thought....
Make sure you set-executionpolicy in the 32 Bit ("Powershell (x86)") version, not the 64 Bit ("Powershell") version, or it won't work...
I'm as bad as the next person for skipping through the guide too quickly then wondering why it didn't work; if you read carefully it does say the above in the guide!
Votes:
0
I have multiple sites but soon as i change default to something else it fails.
XML: The returned XML does not match the expected schema. (code: PE233) -- JSON: The returned JSON does not match the expected structure (Invalid JSON.). (code: PE231)
Any help would be appriciated.
Mat
Votes:
0
Somebody with mulitple sites able to help out here? I only have one for testing :(
PRTG Scheduler |
PRTGapi |
Feature Requests |
WMI Issues |
SNMP Issues
Kind regards,
Stephan Linke, Tech Support Team
Votes:
0
Morning,
I have had this working for 2 years on my work setup. Recently built a UniFi Controller at home and have the script working. But the PRTG controller is getting the following error.
Anyone have any ideas?
Response not well-formed: "(<prtg> <result> <channel>Access Points Connected</channel> <value>4</value> </result> <result> <channel>Access Points Upgradeable</channel> <value>0</value> </result> <result> <channel>Clients (Total)</channel> <value>13</value> </result> <result> <channel>Guests</channel> <value>0</value> </result> <result> <channel>Response Time</channel> <value>1314</value> <CustomUnit>msecs</CustomUnit> </result> </prtg> )" (code: PE132)
Created on May 2, 2019 10:15:14 PM
Last change on May 3, 2019 5:54:04 AM by
Stephan Linke [Paessler Support]
Votes:
1
Interesting. First PowerShell Sensor in this PRTG instance? Set-ExecutionPolicy Unrestricted has been executed? You're using the EXE/Script (Advanced) Sensor? :)
PRTG Scheduler |
PRTGapi |
Feature Requests |
WMI Issues |
SNMP Issues
Kind regards,
Stephan Linke, Tech Support Team
Votes:
1
@Stephan Linke, Tech Support Team.... you are awesome and I am an idiot.
I had done a standard EXE/Script. Not an Advanced one.
Cheers.
Votes:
0
You're welcome :D
PRTGapi |
Feature Requests |
WMI Issues |
SNMP Issues
Kind regards,
Stephan Linke, Tech Support Team
Votes:
0
Hi,
Unfortunately all my sensor values do return a 0 (zero). Only the response time is showing the miliseconds. What am I doing wrong?
Votes:
0
I'm running 5.13.32 and it works perfectly fine. Did you not disable the first run wizard (click) by any chance? Credentials are also correct? Note that if you renamed your default site, it's still named default internally.
Votes:
0
I really like the idea behind this, and are trying to get this to work.
I have a few clients that is managed from their own Unifi Controllers, and are mostly on a private IP address on the internal network.
Is there a way these controllers can be accessed using the Unifi Cloud access portal where it connects remotely to the controller to get the information.
Thanks for excellent work
Votes:
0
The script would probably required to be modified to check against the cloud portal. Depending on the used login and availability of API, this endeavour will ultimately depend on what you can query using the cloud access portal :(
Votes:
0
Would you rather suggest using DynDNS and this way access the local controllers?
Votes:
0
Hi,
I managed to get it working with a port forward on port 8443 on my firewall, and a dynamic DNS address. On another client I just added the port forward, and the sensor is working 100% now.
Than you so much
Louis
Votes:
0
I'd rather go with setting up a VPN instead of exposing this to the web :)
Votes:
0
Hi,
I've been following the guide but I'm struggling to get this working.
I'm getting the following errors:
Sensor XML Custom EXE/Script Sensor
XML: The returned XML does not match the expected schema. (code: PE233) -- JSON: The returned JSON does not match the expected structure (Invalid JSON.). (code: PE231)
Here are the details of our UniFi controller:
- UI:6.0.43.0
- Backend:6.0.43
- Build: atag_6.0.43_14348
I am running PowerShell as administrator and this is the PowerShell Version.
PS C:\Users\AndrewPlatt> Get-Host | Select-Object Version Version ------- 5.1.18362.1171
I have the script saved as Custom Powershell Unifi Status.ps1 in C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML
I'm not sure where I'm going wrong and would appreciate any guidance?
Thanks
Andrew
Created on Jan 17, 2021 10:12:48 AM
Last change on Jan 21, 2021 3:40:17 PM by
Luciano Lingnau [Paessler]
Votes:
0
Andrew,
Can you execute the PowerShell script manually, and paste in what the output looks like? Be sure to include the necessary parameters from the instructions. Please run this from the PRTG probe that is monitoring the Unifi device.
Thanks!
Benjamin Day
[Paessler Support]
Votes:
0
Andrew,
Based on discussions with Unifi, the latest firmware that contains the new Unifi OS no longer supports port "8443". You need to change the port to "443". This then allows the script to execute but in my experience the results provided are all "0" so there is still work to be done to fix this issue.
Votes:
0
Hey wmcdade_tcut,
thank you for your reply.
I'm the script's author and to be honest we've never tried the script with a Cloudkey. It was developed/tested against the unifi controller running on Linux. To be honest the script doesn't care whether the Controller is running on a dedicated system or Cloudkey or anything else. As long as the API is reachable/available and valid credentials are provided, it will work.
And the script does take into account that everyone might pick a different port, this is precisely why it allows you to specify the port using the -port parameter. Example:
For port 8443:
-server '%host' -port '8443' -site 'default' -username 'api-only-user' -password 'api-only-user-password' |
For port 443:
-server '%host' -port '443' -site 'default' -username 'api-only-user' -password 'api-only-user-password' |
If you're only getting zeroes in your result, then something is very much off. Perhaps the user you've created doesn't have access to anything. Because if the endpoint was wrong or the user wasn't able to login you would get a different error.
One way to make sure that you're querying the correct port is opening the following URL in your browser: "https://unificontroller.domain.tld:443/api/" (or "https://unificontroller.domain.tld:8443/api/" for port 8443)
You should see the following:
{"meta":{"rc":"error","msg":"api.err.LoginRequired"},"data":[]}
If you don't, something else is off and/or this isn't the correct port.
Cheers!
Created on Jan 21, 2021 3:52:10 PM by
Luciano Lingnau [Paessler]
Last change on Jan 22, 2021 6:56:24 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hi Luciano,
I fear more has changed with the OS than is being understood. The Windows/Linux and Mac versions of the software are listed as "legacy" on the Unifi site, ref: "https://www.ui.com/download/unifi/unifi-legacy".
Using your method of testing on a hardware version of the latest Unifi OS does not result in the response you assert.
https://[controllername]:8443/api/ fails, therefore this port, as stated by Unifi multiple times, is not supported. The script above should not refer to this being the default port.
https://[controllername]:443/api/ redirects the browser to https://[controllername]/login?redirect=%2Fapi%2F which is the device login page.
I have tested the legacy software version, this being UniFi Network Controller 6.0.43 for Windows, release date: 2020-12-28 and this does respond in the manner you suggest.
Considering the software version is legacy, it would appear you are testing a version that continues to support port 8443 and responds in the same manner is it previous had. The latest hardware version that uses the latest "Unifi OS" does not support port 8443 or does it respond with any data to the script above other than “Response Time”.
Executing the above script using the 'root' user does not report any data for:
- Access Points Connected - Access Points Upgradeable - Clients (Total) - Guests
See example here: https://i.imgur.com/XiKgCbU.png
Using a separate account created specifically for the purpose of monitoring the controller initially as a read only, limited admin gives the same "0" response as above. Upgrading this account to a Super Admin also results in the same "0" response.
This result has been seen on both a UCK-G2 (Cloudkey G2) and UDM-Pro (Dream Machine Pro), both of which have the following FW installed at the time of the tests.
UCK-G2 - https://community.ui.com/releases/UniFi-Cloud-Key-Firmware-2-0-24/b6684f1e-8542-4660-bc0b-74e0634448e8 UDM-Pro - https://community.ui.com/releases/UniFi-Dream-Machine-Firmware-1-8-5/ff2ef03c-9659-4d02-a6f3-9835569059f8
Note that both use Network Controller 6.0.43 https://community.ui.com/releases/UniFi-Network-Controller-6-0-43/b28bb453-927a-4dd8-82f7-40af28505510.
I understand Network Controller 6.0.43 is listed within the software version which is what you are using to test, but there must be differences for it to respond in the manner it does on their hardware installed versions.
Created on Jan 22, 2021 11:29:52 AM
Last change on Jan 25, 2021 7:43:27 AM by
Luciano Lingnau [Paessler]
Votes:
0
Hello wmcdade_tcut, thank you for your reply.
To keep things tidier here I'll use these little boxes to quote/give context to maybe try and keep my reply easier to understand. Since you address multiple different things in your text :)
Starting with:
I fear more has changed with the OS than is being understood. The Windows/Linux and Mac versions of the software are listed as "legacy" on the Unifi site, ref: "https://www.ui.com/download/unifi/unifi-legacy". |
I can't say for certain without working for Ubiquiti, but I'm pretty certain they're not moving their Linux controller to "legacy" anytime soon. This looks more like it due to the way that the website is set-up. You will see the "UniFi Network Controller 6.0.43 for Debian/Ubuntu Linux and UniFi Cloud Key" on every sub-menu item (categories). No matter what you select on the left side.
The script above should not refer to this being the default port. [...] I have tested the legacy software version, this being UniFi Network Controller 6.0.43 for Windows, release date: 2020-12-28 and this does respond in the manner you suggest. Considering the software version is legacy, it would appear you are testing a version that continues to support port 8443 and responds in the same manner is it previous had. The latest hardware version that uses the latest "Unifi OS" does not support port 8443 or does it respond with any data to the script above other than “Response Time”. |
While I appreciate your feedback and input, if you refer to the only UniFi - Ports Used that I could locate, it states that port 8443 is "Port used for controller GUI/API as seen in a web browser". But like I said earlier, it's not my goal to get the default port right, just to have it configurable in the script.
Executing the above script using the 'root' user does not report any data for: Access Points Connected - Access Points Upgradeable - Clients (Total) - Guests See example here: https://i.imgur.com/XiKgCbU.png Using a separate account created specifically for the purpose of monitoring the controller initially as a read only, limited admin gives the same "0" response as above. Upgrading this account to a Super Admin also results in the same "0" response. |
My suggestion for you to troubleshoot these zero results is to use the -debug option. This will give you a better idea of what is going on (or what the controller is replying). Alternatively you can run the script in powershell ISE and inspect the values of the variables yourself. This may give you a better idea of what is going on and why it is behaving differently for you.
As far as I'm aware (and based on the replies from other customers) there's nothing gravely wrong with the script. And please keep in mind that this is all there there is. PRTG doesn't include native sensors for Ubiquiti's Unifi ecosystem as of now. This script just proves it is possible but as you noticed you might have to tweak something to get it working in your scenario.
But this is a forum. So maybe another customer/user will be able to step in and confirm whether the script is working with their cloudkey or not. Maybe someone can even suggest a fix/workaround. But at the moment the script is as it is I'm afraid.
Cheers!
Votes:
0
Luciano,
Thank you for looking into this for me, however I feel you are incorrect. I have already sent the response from Ubiquiti to your colleague who has pointed me here to continue with this issue. So here it is again.
You assert the script is correct but Ubiquity have twice replied to questions about this with the following:
Ubiquiti themselves say port 8443 is not supported. In addition port 8443 is also no longer listed in the firmware release notes.
See section: Other notes > Local portal available here: https://<local IP address>
There is no ":8443" for this connection contrary to previous versions. I assume the version of the software you are testing on still uses port 8443.
From the above, the portal/api now use port 443. This means your script, albeit editable, is incorrect to maintain that the default port is "8443".
Furthermore, I have attempted to use your "-debug" method but this, like your script, appears to be written for the software version, due to it referring to HKLM on the computer executing the script. See below.
The script I am using is direct from the page it is published and it has not been edited other then to complete the sections required. I have also amended the port from 8443 to 443 as directed by Ubiquiti.
Prior to the latest large update from Unifi which included the Unifi OS, the script worked without problem. Once the FW upgrade was installed, the script ceased to work. Further investigation highlighted the port error and amending this now allows for the script to integrate the hardware, but does not result in any results. This is where I am stuck and all evidence points towards a change to the software that is not compatible with your script for those using a hardware version of the Network Controller.
Votes:
0
Hello wmcdade_tcut, thank you for the update.
The script assumes that it will be run on the PRTG Server, so it looks for the correct path to store the logs. Perhaps you ran it somewhere differently but the error basically is: "I can't find the registry path that will tell me where to store the logs".
On line 141 of the script you could simply set the [string]$logPath to something like "C:\Users\%YOURUSERNAME%\Documents\TemporaryFolderForLogs\" (The folder must exist) and it should be able to write the logs there.
This will generate a file like "unifi_sensor2021-25-01-05-02-33_log.json" - In this file you should get a list of all devices available on this controller. Something like this(I've ommited some details with [...] in the reply for the sake of security and to keep it short:
{ "meta": { "rc": "ok" }, "data": [ { "_id": "5867779ce4b024883172a48c", "adopted": true, "antenna_table": "", "board_rev": 30, [...] "vwireEnabled": false, "uplink_table": "", "num_sta": 0, "user-num_sta": 0, "user-wlan-num_sta": 0, "guest-num_sta": 0, "guest-wlan-num_sta": 0 }, { "_id": "58677798e4b024883172a48a", "adopted": true, "antenna_table": "", "board_rev": 27, [...] "vwireEnabled": false, "uplink_table": "", "num_sta": 5, "user-num_sta": 5, "user-wlan-num_sta": 5, "guest-num_sta": 0, "guest-wlan-num_sta": 0 } ] }
From all devices in this list, the script will only care about devices of the type ""type": "uap",". It will iterate over all entries within this JSON array and get the statistics needed for the script's output. The script contains comments in each step indicating what is going on, so it should be easy to figure out what's wrong once you have that output.
If you manage to get a JSON file this way, please share it with the support colleagues that you've contacted and they can forward me the file, I don't mind having a look. With this file at hand it should be relatively easy to figure out what's wrong. (Assuming the information we need is in the file. If it isn't we have a whole new problem). But in this case I would rather wait for the feedback from other users before adjusting the script.
Part of the problem is that Ubiquiti doesn't really have (Or at least when I wrote the script I wasn't able to find it) an official documentation for their API, so basically all inspiration comes from playing with the API and looking at examples from script that other people wrote.
Short Update(29/jan/2021):
I juust realized it's possible to test the script against the latest available version of the controller by running the script against the demo environment set-up by unifi. For example:
& '.\Custom Powershell Unifi Status.ps1' -server 'demo.ui.com' -port '443' -site 'default' -username 'unifi-demo' -password 'unifi-demo' |
The output is(Formatted like XML for easier understanding/reading):
<prtg> <result> <channel>Access Points Connected</channel> <value>118</value> </result> <result> <channel>Access Points Upgradeable</channel> <value>118</value> </result> <result> <channel>Clients (Total)</channel> <value>1180</value> </result> <result> <channel>Guests</channel> <value>0</value> </result> <result> <channel>Response Time</channel> <value>1025</value> <CustomUnit>msecs</CustomUnit> </result> </prtg>
At the time of this writing, this public demo instance is running version 5.11.39 of the controller. On port 443 but as demonstrated, the script can handle it.
Cheers!
Created on Jan 25, 2021 4:16:44 PM by
Luciano Lingnau [Paessler]
Last change on Jan 29, 2021 9:32:53 AM by
Luciano Lingnau [Paessler]
Votes:
0
Luciano,
Thank you for the response. I will update you here as to my findings after following the steps provided.
I may be misunderstanding your first step as I have made the swap as you describe:
This does not result in a debug file being created in the location set in the path. The folder does exist and has the "\Everyone" permission set to "Full Control".
Additionally a file in the same format you give as an example "unifi_sensor2021-25-01-05-02-33_log.json" is created in the "C:\Program Files (x86)\PRTG Network Monitor\Custom Sensors\EXEXML\Logs (sensors)" folder. However these files do not contain the information you give as an example:
"\n\u003c!doctype html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n\u003cmeta charset=\"utf-8\"\u003e\n\u003cmeta name=\"viewport\" content=\"width=device-width,initial-scale=1\"\u003e\u003clink href=\"/2.css\" rel=\"stylesheet\"\u003e\u003c/head\u003e\n\u003cbody\u003e\n\u003cdiv id=\"root\"\u003e\u003c/div\u003e\n\u003cscript type=\"text/javascript\" src=\"/vendor.0306759b.chunk.js\"\u003e\u003c/script\u003e\u003cscript type=\"text/javascript\" src=\"/main.d8e6c715.js\"\u003e\u003c/script\u003e\u003c/body\u003e\n\u003c/html\u003e\n"
Lastly your test using the Unifi demo server (demo.ui.com) for which you state is running version "5.11.39 of the controller" will function correctly. This is on the old version of the Network Controller software that was working, which I have stated previously. The current version of the Network Controller software is 6.0.43. The full change log from version 5.x to 6.x can be found here:
With the latest patched version change log being found here:
If there is a mistake in line 141 of the edited script can you please provide the full line of script and I will replace this within the one I have.
I do still state that your tests on the old version of the Network Controller are causing the confusion. I have tested your script on both a UDM-PRO and UCKG2 both on the lest firmware and both produce no results.
This is only a possibility but Unifi have removed the site feature from the latest edition of their Network Controller. This may be part of the problem, but I am less of an expert compared to yourself.
Votes:
0
Hey wmcdade_tcut, thank you for your reply.
That's not what I meant regarding line 141 but since you got the output of unifi_sensor2021-25-01-05-02-33_log.json either way, that's sufficient for me. And it doesn't look good. Something went terribly bad and apparently the script got something but definitely not the JSON we were after. The sensor definitely won't work with that "output"...
Your point about the lack of multi-site support however is a very good point:
This is only a possibility but Unifi have removed the site feature from the latest edition of their Network Controller. This may be part of the problem, but I am less of an expert compared to yourself. |
I had a brief look on the KB and found this which also confirms this: UniFi Cloud Key Firmware 2.0.24
And I don't fancy changing the script before someone at least figure outs whether that's a bug or not. I even suspect that it is a bug on Unifi's side. But I don't want to blame them just yet so that's just my first guess, not my official statement.
Either way, that could explain the behaviour you're seeing. On line #66 the script explicitly queries a specific site:
$jsonresultat = Invoke-Restmethod -Uri "$controller/api/s/$site/stat/device/" -WebSession $myWebSession
And it's hard to guess the syntax when there shouldn't be a site. Maybe you could try this change (at your own risk):
$jsonresultat = Invoke-Restmethod -Uri "$controller/api/s/stat/device/" -WebSession $myWebSession
But again without any official statement or feedback from ubiquiti, it would be pure luck if that worked. Feel free to contact Ubiquiti's support again and ask if they can confirm whether /api/s/$site/stat/device/ (or /api/s/default/stat/device/) is still valid in the latest firmware. While you're at it you could ask for a confirmation of whether the change is intentional or not. My intention is not to push you back an forth with unifi's support. But it would be great to know whether that's a bug or intentional.
When I look at the unifi_sh_api (shell library) for version 6.0.45 it still shows $baseurl/api/s/$site/stat/device (for example in unifi_list_devices()) so my assumption is that these should still work.
Something else that was discussed in the topics is that potentially, the "default" site no longer exists, this could also explain the issue. When you open the web-interface on your controller (after you've logged-in) check the URL, it will be something like:
https://unifi.domain.tld/manage/site/btqapob9/dashboard |
In this case, btqapob9 is what you need to define as -site 'btqapob9' when you run the script.
I hope the information above helps you find a solution to the issue. Or perhaps Ubiquiti's support can enlighten you about what's going on and why the firmware update caused such a side-effect..
Cheers!
Votes:
0
Luciano,
I will try your suggestions on Monday and also contact Unifi to ask the questions that have been raised. Thank you for the help thus far. Hopefully we can get this resolved.
In regards to your question about the URL, this currently looks like this:
https://[controllerhostname]/network/site/default/v2/dashboard
This would imply "Default is still in use for the site". Further to this issue, you are most likely correct about it being a bug. The multi-site functionality is returning in the next FW release. See here: https://www.reddit.com/r/Ubiquiti/comments/l76p4l/unifi_network_controller_6151/
I have checked on our UDB-PRO and the current Network Controller is 6.0.43.0 and this appears to be current. I suspect the FW is on a gradual release.
Votes:
0
Hello,
I'm very excited about this sensor, but I'm having issues getting it to work. I've run the script in PowerShell ISE and it works. I'm using the following for environmental variables:
-server '%host' -port '8443' -username '%windowsuser' -password '%windowspassword'
I keep getting the error:
!!The access has been denied. To resolve this issue, check your Credentials for Windows Systems in the device settings. (code: PE095)
I've confirmed 3 times that the windows username / password are correct and they match what I had when I manually ran the script, so I'm thinking there is something else wrong....
Created on Feb 11, 2021 5:29:15 PM
Last change on Feb 12, 2021 11:17:21 AM by
Felix Wiesneth [Paessler Support]
Votes:
0
Hi there,
Did you also configured in the Sensor that the Windows credentials should be transmitted to the script? This needs to be configured in the corresponding option in the Sensor settings.
Votes:
0
Luciano,
Apologies for the delay. We have had other issues with the UDMP that have taken priority.
I have set up a test environment with a CloudKey G2 (UCK-G2) with a single UAP-AC-M and one device connected to its wireless network. I have taken a fresh copy of the above script and am using this configured with the following parameters:
[string]$server = '%host', [string]$port = '443', [string]$site = 'default', [string]$username = 'root', [string]$password = 'password123', [switch]$debug = $false
Additionally to this script via the EXE/ Advanced sensor I have two other SSH based sensors. These are:
- SSH Load Average
- SSH Meminfo
Both of these sensors are using the "Credentials for Linux/Solaris/macOS (SSH/WBEM) Systems" part of the Device settings and both sensors function correctly. This concludes the SSH user details being used are correct.
The XML Custom EXE/Script Sensor is still producing "0" values that a clearing incorrect.
No response from Unifi on the subject of the changes they have made and if they are to stay.
The UCK-G2 is running the Release Channel: Official but I will proceed with swapping to Beta to see if there are any changes in the later, to-be-released, updates.
Votes:
0
Hi wmcdade_tcut,
thank you for granting us temporary access to your setup. We've managed to locate the issue (Some inexplicable difference in the API) that allowed us to suggest a workaround. I've also now documented the workaround in this KB Article under a section called "Workaround for UDM Pro API". This should help anyone who runs into a similar problem.
We located a hint to the "issue" on https://ubntwiki.com/products/software/unifi-controller/api - Which suggested that the "UDM Pro API" works slightly differently. Luckily the change is so small that with minor changes the script still works.
I'm slightly annoyed at unifi because my assumption that the authentication worked was wrong. Whenever the script queried the wrong path it still got an HTTP 200 response (with garbage). This lead to me assuming that the authentication was working which it wasn't.
Anyway, I'm happy to report that apparently all is fine again. With the small adjustments the script will work on the Cloud key but I've left the original script unmodified for the time being.
Thank you for your patience! Cheers!
Luciano Lingnau [Paessler Support]
Votes:
1
Hi there, the script works with the new 6.0.45+ version when you change the following lines:
Line 23: FROM: [string]$port = '8443', TO: [string]$port = '443',
Line 55: FROM: $null = Invoke-Restmethod -Uri "$controller/api/login" -method post -body $credential -ContentType "application/json; charset=utf-8" -SessionVariable myWebSession
TO: $null = Invoke-Restmethod -Uri "$controller/api/auth/login" -method post -body $credential -ContentType "application/json; charset=utf-8" -SessionVariable myWebSession
and
Line 66: FROM: $jsonresultat = Invoke-Restmethod -Uri "$controller/api/s/$site/stat/device/" -WebSession $myWebSession
TO: $jsonresultat = Invoke-Restmethod -Uri "$controller/proxy/network/api/s/$site/stat/device/" -WebSession $myWebSession
Thats it.
Have fun
Votes:
0
Based on the best answer of this I have this script working well for each of my sites. What I want to now do is setup limits so it flags if an AP is down (https://www.paessler.com/support/how-to/limits) but I am having issues.
I know how many access points are on each site so want it to either flag is the number of connected devices drops or the access points disconnected goes to 1 but I do not seem to be able to get that to work. I have a site with 1 down at the moment so it should flag but when I try the limits on the site with all 11 working it flags it as down.
We use PRTG for all our monitoring so would pick up that an AP is down rather than logging into the Unifi controller.
Votes:
0
Hi Matt,
If I understand you correctly, you have a total of 11 AP's, and want to get the sensor to Down state when only 10 are connected.
If that is the case, you can set the "Lower Error limit" in the "Connected AP's" channel to 11, so the sensor goes Down once there are less than 11 AP's.
Kind regards,
Sasa Ignjatovic, Tech Support Team
Votes:
0
Hi, if you're still answering questions, I have run into a problem where after following the guide there are no sensors to select. Any ideas?
Votes:
0
Hello jhodonald,
Can you please explain more in detail what you mean with "there are no sensors to select"?
I am asking since you are creating a Exe/Script Advanced sensor, where you can only select the script that you want to use, there shouldn't be any sensor selection here.
Kind regards,
Sasa Ignjatovic, Tech Support Team
Add comment