Blog Series: Monitoring using PowerShell: Part three – Using Powershell to monitor Unifi Controllers

Hi All,

My next couple of blogs will be a series of blogs where I will be explaining on how to use PowerShell for the monitoring of critical infrastructure. I will be releasing a blog every day that will touch on how to monitor specific software components, but also network devices from Ubiquiti, third-party API’s and Office365. I will also be showing how you can integrate this monitoring in current RMM packages such as Solarwinds N-Central, Solarwinds RMM MSP and even include the required files to import the  monitoring set directly into your system.


Requirements:

  • Ubiquiti Unifi Controller running 5.x.
  • Read-only user on all sites.
  • PowerShell v3 or higher

Creating the monitoring sets:

Before we start, credit where credit is due: Most of this post is based on the code found on this reddit post. Connecting to the Unifi controller via the API is completely based on that post and I’ve only modified a few small parts to make connecting easier, I also want to make sure you understand what we’re doing here; We will be using the REST API to query the controller for information, not the access points, switches, or routers themselves. You can also use the examples in this post to connect to several other APIs.

Now that we’re clear lets dive straight into the connecting and querying the portal for the information.

param(
[string]$URL = 'yourcontroller.controller.tld',
[string]$port = '8443',
[string]$User = 'APIUSER',
[string]$Pass = 'SomeReallyLongPassword',
[string]$SiteCode = 'default' #you can enter each site here. This way when you assign the monitoring to a client you edit this to match the correct siteID.
)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
[string]$controller = "https://$($URL):$($port)"
[string]$credential = "`{`"username`":`"$User`",`"password`":`"$Pass`"`}"
try {
$null = Invoke-Restmethod -Uri "$controller/api/login" -method post -body $credential -ContentType "application/json; charset=utf-8"  -SessionVariable myWebSession
}catch{
$APIerror = "Api Connection Error: $($_.Exception.Message)"
}

After executing the commands above we’ve established a connection to the unifi controller, we can check if the connection was succesfull by calling the $APIError variable. The Unifi API sometimes give somewhat strange errors which account to a credentials issue 99% of the time.

Based on the connection we can try to connect to the Unifi portal with different queries. I’ve generated a small list of possible queries and of course you can change these to suit your needs:

Check if devices need an update:

try {
$APIResult = Invoke-Restmethod -Uri "$controller/api/s/$SiteCode/stat/device/" -WebSession $myWebSession
}catch{
$APIerror = "Query Failed: $($_.Exception.Message)"
}
Foreach ($entry in ($APIResult.data | where-object { $_.upgradable -eq $true})){
$DeviceUpgrade += "Upgrades Available on $($Entry.Name)"
}
if(!$APIError){ $APIError = "Healthy"}
if(!$DeviceUpgrade){ $DeviceUpgrade = "Healthy"}

Check if all devices are online:

try {
$APIResult = Invoke-Restmethod -Uri "$controller/api/s/$SiteCode/stat/device/" -WebSession $myWebSession
}catch{
$APIerror = "Query Failed: $($_.Exception.Message)"
}
Foreach ($entry in ($APIResult.data | where-object { $_."state" -ne "1"})){
$DeviceState += "Device not connected $($Entry.Name)“
}
if(!$APIError){ $APIError = "Healthy"}
if(!$DeviceState){ $DeviceState = "Healthy"}

Check if device health is OK:

try {
$APIResult = Invoke-Restmethod -Uri "$controller/api/s/$SiteCode/stat/device/" -WebSession $myWebSession
}catch{
$APIerror = "Query Failed: $($_.Exception.Message)"
}
Foreach ($entry in ($APIResult.data)){
if( [math]::Round($entry.'system-stats'.cpu) -gt "80.0") { $DeviceHealthCPU += " `n $($entry.name) has CPU usage of $($entry.'system-stats'.cpu)%" }
if( [math]::Round($entry.'system-stats'.mem) -gt "80.0") { $DeviceHealthMEM += " `n $($entry.name) has a memory usage of $($entry.'system-stats'.mem)%" }
if( [math]::Round($entry.'system-stats'.uptime) -lt "300") { $DeviceHealthUptime += " `n $($entry.name) has an uptime of $($entry.'uptime') seconds" }
}
if(!$APIError){ $APIError = "Healthy"}
if(!$DeviceHealthCPU){ $DeviceHealthCPU = "Healthy"}
if(!$DeviceHealthMEM){ $DeviceHealthMEM = "Healthy"}
if(!$DeviceHealthUptime){ $DeviceHealthUptime = "Healthy"}

Get WAN status from Unifi Gateway:

try {
$APIResult = Invoke-Restmethod -Uri "$controller/api/s/$SiteCode/stat/device/" -WebSession $myWebSession
}catch{
$APIerror = "Query Failed: $($_.Exception.Message)"
}
Foreach ($entry in ($APIResult.data.wan1 | where-object { $_.enable -eq "true"})){
if($entry.up -eq $false) { $WAN1Health = " `n $($entry.name) is down" }
}
Foreach ($entry in ($APIResult.data.wan2 | where-object { $_.enable -eq "true"})){
if($entry.up -eq $false) { $WAN2Health = " `n $($entry.name) is down" }
}
if(!$APIError){ $APIError = "Healthy"}
if(!$WAN1Health){ $WAN1Health = "Healthy"}
if(!$WAN2Health){ $WAN2Health = "Healthy"}

Get blocked STP Ports

try {
$APIResult = Invoke-Restmethod -Uri "$controller/api/s/$SiteCode/stat/device/" -WebSession $myWebSession
}catch{
$APIerror = "Query Failed: $($_.Exception.Message)"
}
Foreach ($entry in ($APIResult.data.port_table | where-object { $_.stp_state -match "discard"})){
$STPError += "`n$($entry.name) has been blocked due to STP issues."
}
if(!$APIError){ $APIError = "Healthy"}
if(!$STPError){ $STPError = "Healthy"}

And thats the scripts for this session! The next session I’ll be dedicating to automated maintenance on the unifi controller and devices.

Downloads for RMM packages:

N-Central 11.0+ – Unifi Controller package

6 thoughts on “Blog Series: Monitoring using PowerShell: Part three – Using Powershell to monitor Unifi Controllers

  1. Pingback: Blog Series: Monitoring using PowerShell: Part four – Using Powershell to update and maintain unifi devices – CyberDrain

  2. alan

    Hey, I ran into a problem with the script not working. “Unable to connect to Unifi controller. The request was aborted: Could not create SSL/TLS secure channel.”

    Reply
    1. Kelvin Tegelaar Post author

      Hi Alan,

      Do you have the following 2 lines somewhere near the top of the script?

      [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
      [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
      

      These cancel the certificate checks, and sets up TLS1.2. If that does not work, then double check if you’ve entered the correct port-numbers. You need to use the same port as the Unifi webmanagement portal is on, not the Unifi Inform port.

      Reply
  3. MrFish

    Appreciate your work, and if this works it’s wonderful news! BUT, it seems to be missing an xml file to import it to Ncentral? I get a zip with amp files but no xml.

    Thanks in advance and keep up the good work!

    Reply
    1. Kelvin Tegelaar Post author

      Hi Oscar,

      With AMP based monitoring you do not need the XML file. Simply open automation manager and upload this AMP to your instance, then go to Administration -> Service Management -> custom services and click Add, now you select the AMP and you’ve created a custom monitoring set.

      Good luck!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.