# PRTG-Ubiquiti Sensors
#
# Uses the Ubiquiti Controller REST-Api to collect additional information about the WLAN
# Send a main Feedback about the Sensor itself and global values
# Additional HTTPPush Sensors are used to send Datra per SSID and Channel
#
# 20170512 Ver 0.7 FC Initial Version with REST-API
# 20170515 Ver 1.0 FC First version with additional HTTPPush sensors
# 20170531 Ver 1.1 FC Remove custom Unit String
# 20170710 Ver 1.2 FC Enforce TLS 1.1
# 20201130 Ver 1.3 FC Added debugging and SkipCertCheck, enhanced error handing
# 20201201 Ver 1.4 FC Debugging Output parameter and Sensornames
# 20211216 Ver 1.5 FC Bugfix mit CertCheck und Version Check minimum 3 -> 7, Exit Code korrektur
[CMdLetBinding()]
param(
[string]$controlleruri = "https://192.168.178.8:8443", # Url to access the ubiqiti controller Service
[string]$site = 'default', # name of the ubiquiti site to query
[string]$username = 'RESTAPI', # valid user account of an Admin (ReadOnly is fine)
[string]$password = 'REST4PRTG', # corresponding password
[string]$httppushurl = 'http://192.168.178.11:5050/ubiquitiy-', #prefix of HTTP-Sensors
[int]$maxretries = 3, # maximum numbers of retries to grab authToken and JSON_Data
[switch]$SkipCertificateCheck = $false
)
Write-verbose "PRTG-Ubiquiti-MSXFAQ:Start"
Write-verbose "Param: controlleruri : $($controlleruri)"
Write-verbose "Param: site$ : $($site)"
Write-verbose "Param: username$ : $($username)"
Write-verbose "Param: password$ : $($password)"
Write-verbose "Param: httppushurl : $($httppushurl)"
Write-verbose "Param: maxretries : $($maxretries)"
Write-verbose "Param: SkipCertificateCheck: $($SkipCertificateCheck)"
if ($SkipCertificateCheck) {
Write-Verbose " Skip CertificateCheck enabled"
#Ignore SSL Errors, maybe not required, because Invoke-RESTMethod has a Switch
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
}
Write-Verbose " Loading system.web for URL Encoding"
Add-Type -AssemblyName system.web # required for URL Enconding
Write-Verbose "Enforce TLS1.1 or higher. Ubiquiti 5.4.18 does not support tls 1.0 anymore"
$ValidTLS = [System.Net.SecurityProtocolType]'Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $ValidTLS
Write-Verbose "PRTG-Ubiquiti-MSXFAQ:Check PS-Version"
# Confirm Powershell Version.
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-Output ""
Write-Output "1"
Write-Output "Powershell Version is $($PSVersionTable.PSVersion.Major) Requires at least 3. "
Write-Output ""
Write-Output "PRTG-Ubiquiti-MSXFAQ:Check PS-Version failed"
Exit
}
write-Verbose "Build CredentialJSON"
[string]$credential = "`{""username"":""$username"",""password"":""$password""}"
write-Verbose "CredentialJSON: $($credential)"
# Start debug timer
$queryMeasurement = [System.Diagnostics.Stopwatch]::StartNew()
Write-Verbose "Try to get Authentication Token"
$trycount=1
$restresult=$null
while ($trycount -lt $maxretries) {
try {
Write-verbose "PRTG-Ubiquiti-MSXFAQ:Download Login Token from Controller, try $trycount"
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$restresult=Invoke-Restmethod `
-Uri "$controlleruri/api/login" `
-method POST `
-body $credential `
-ContentType "application/json; charset=utf-8" `
-WebSession $Websession `
-SkipCertificateCheck:$SkipCertificateCheck
$trycount=$maxretries
}
catch{
Write-verbose "CATCH $($_)"
$trycount++
}
}
if ($restresult.meta.rc -eq "ok") {
Write-Verbose "Getting Authentication Cookie SUCCESSFUL Result.meta.rc -eq ok"
}
else {
Write-Verbose "NO Authentication Cookie received - Stopping"
Write-Output ""
Write-Output "1"
Write-Output "No Session Authentication Failed: $($_.Exception.Message)"
Write-Output ""
Write-Output "PRTG-Ubiquiti-MSXFAQ:Download Login Token failed. Exitcode:3"
Exit 3
}
foreach ($cookie in $WebSession.cookies.GetCookies($controlleruri)) {
write-verbose "Cookie Name: $($cookie.name) = $($cookie.value)"
}
#Query API providing token from first query.
$jsonresult=$null
$trycount=1
Write-Verbose "Try to get $($controlleruri)/api/s/$($site)/stat/device/"
while ($trycount -lt 3) {
try {
Write-verbose "PRTG-Ubiquiti-MSXFAQ:Download Controller Data from $controlleruri trycount $trycount"
$jsonresult = Invoke-Restmethod `
-Method POST `
-Uri "$controlleruri/api/s/$site/stat/device/" `
-WebSession $WebSession `
-SkipCertificateCheck:$SkipCertificateCheck `
-verbose
$trycount=$maxretries
}
catch{
$trycount++
}
}
if ($jsonresult.meta.rc -eq "ok") {
write-verbose "jsonresult.meta.rc -eq ok"
}
else {
Write-Verbose "NO Authentication Cookie received -Stopping"
Write-Output ""
Write-Output "1"
Write-Output "API Query Failed: $($_.Exception.Message)"
Write-Output ""
Write-Output "PRTG-Ubiquiti-MSXFAQ: Download Controller Data FAILED. Exitcode:4"
Exit 4
}
# Stop debug timer
$queryMeasurement.Stop()
Write-verbose "PRTG-Ubiquiti-MSXFAQ:Generating Data"
foreach ($entry in $jsonresult.data.vap_table) {
Write-verbose "-----------------------------------------------------"
Write-verbose "PRTG-Ubiquiti-MSXFAQ: WLAN $($entry.essid) on $($entry.radio) "
Write-verbose "PRTG-Ubiquiti-MSXFAQ: Clients $($entry.num_sta)"
Write-verbose "PRTG-Ubiquiti-MSXFAQ: Channel $($entry.channel)"
$prtgresult = '
TotalClients
'+($entry.'num_sta')+'
0
Channel
'+($entry.'channel')+'
0
RX-Bytes
'+($entry.'rx_bytes') +'
0
Difference
Bytes
RX-Errors
'+($entry.'rx_errors') +'
0
Difference
Pakete
RX-dropped
'+($entry.'rx_dropped') +'
0
Difference
Pakete
TX-Bytes
'+($entry.'tx_bytes') +'
0
Difference
Bytes
TX-Errors
'+($entry.'tx_errors') +'
0
Difference
Pakete
TX-dropped
'+($entry.'tx_dropped') +'
0
Difference
Pakete
'
#$prtgresult
$uri = ($httppushurl+$guid+$($entry.essid)+"-"+$($entry.radio))
Write-verbose "ESSID : $($entry.essid)"
Write-verbose "Radio : $($entry.radio)"
Write-verbose "Sensorname: $($guid+$($entry.essid)+"-"+$($entry.radio))"
Write-verbose "PRTG-Ubiquiti-MSXFAQ: Sending Data to $($uri)"
#$debugfile = ([string](get-date).tostring("hhmmssfff") + ".txt")
#Write-verbose "PRTG-Ubiquiti-MSXFAQ: Sending Debug to $debugfile"
#$prtgresult | out-file $debugfile
$Answer=Invoke-Webrequest `
-method 'GET' `
-URI ($uri + "?content="+[System.Web.HttpUtility]::UrlEncode($prtgresult)) `
-usebasicparsing
Write-verbose "WebRequest $($answer.rawcontent)"
if ($answer.Statuscode -ne 200) {
write-warning 'Request to PRTG failed. Exitcode:1'
exit 1
}
}
Write-verbose "PRTG-Ubiquiti-MSXFAQ: Done sending individual WLANs"
Write-verbose "PRTG-Ubiquiti-MSXFAQ: Start generating summary"
$apCount = 0
Foreach ($entry in ($jsonresult.data | where-object { $_.state -eq "1" -and $_.type -like "uap"})){
$apCount ++
}
$apUpgradeable = 0
Foreach ($entry in ($jsonresult.data | where-object { $_.state -eq "1" -and $_.type -like "uap" -and $_.upgradable -eq "true"})){
$apUpgradeable ++
}
$userCount = 0
Foreach ($entry in ($jsonresult.data | where-object { $_.type -like "uap"})){
$userCount += $entry.'ng-num_sta'
}
$guestCount = 0
Foreach ($entry in ($jsonresult.data | where-object { $_.type -like "uap"})){
$guestCount += $entry.'ng-guest-num_sta'
}
#Write Results
Write-Output ""
Write-Output ""
Write-Output " "
Write-Output " Clients (Total)"
Write-Output " $($userCount)"
Write-Output " "
Write-Output " "
Write-Output " Access Points Connected"
Write-Output " $($apCount)"
Write-Output " "
Write-Output " "
Write-Output " Access Points Upgradeable"
Write-Output " $($apUpgradeable)"
Write-Output " "
Write-Output " "
Write-Output " Guests"
Write-Output " $($guestCount)"
Write-Output " "
Write-Output " "
Write-Output " Load"
Write-Output " $($jsonresult.data.sys_stats.loadavg_5)"
Write-Output " "
Write-Output " "
Write-Output " Response Time"
Write-Output " $($queryMeasurement.ElapsedMilliseconds)"
Write-Output " msecs"
Write-Output " "
Write-Output ""
Write-Verbose "PRTG-Ubiquiti-MSXFAQ:End. Exitcode:0"
exit 0