ralpht
Goto Top

PRTG und Ubiquiti

Moin,

ich wollte folgendes Script auf PRTG zum Laufen bringen:

Überwachung von Ubiquiti mit PRTG

PRTG läuft auf einem Server 2016. Dieses Script startet nicht mit Powershell 5.1. Dann habe ich auf diesem Server Powershell 7 installiert. Damit funktioniert es.

Jetzt habe ich folgendes Problem:

PRTG startet dieses Script nicht, weil eben intern die Version 5.1 verwendet wird. Wie bekomme ich das jetzt zum Laufen?
Ich hatte überlegt Powershell 7 als default auf dem Server zu setzen. Dazu habe ich aber nichts gefunden. Oder kann man PRTG dazu bewegen, dass das Programm Powershell 7 nimmt?

Dann hatte ich mal versucht, im Script die Versionsabfrage von 7 auf 5 zu setzen. Läuft natürlich nicht, da das Script wohl wirklich die Version 7 benötigt.
Von Powershell habe ich keine Ahnung.

Hat jemand eine Idee, wie man diesen Sensor zum Laufen bekommt?

Content-ID: 4651515795

Url: https://administrator.de/contentid/4651515795

Ausgedruckt am: 21.11.2024 um 21:11 Uhr

4400667902
4400667902 16.11.2022 aktualisiert um 08:19:02 Uhr
Goto Top
Das einzige was das Skript benutzt was es erst ab PS 6.0 gibt ist der Parameter
-SkipCertificateCheck:$SkipCertificateCheck
von Invoke-Restmethod. Den kannst du aber entfernen da der ServicePoint Manager schon zum Ignorieren von Zertifikatsfehlern aufgefordert wurde wenn per Skript-Parameter aktiviert wurde.
Wenn du dann noch den Versionscheck abänderst auf
if ($PSVersionTable.PSVersion.Major -lt 3) {
Sollte es auch mit der 5er laufen, denn ansonsten wird nichts anderes verwendet was die Version 7er rechtfertigt, absolute Standardkost.

Uk.
RalphT
RalphT 16.11.2022 aktualisiert um 09:18:06 Uhr
Goto Top
Hallo Uk,

die Zeile

-SkipCertificateCheck:$SkipCertificateCheck

habe ich entfernt und den Versionscheck entsprechend geändert.

Jetzt kommt beim Aufruf folgender Fehler:

API Query Failed
Download Controller Data FAILED. Exitcode:4

Mit PS 7 läuft es noch weiterhin.

Kannst du damit was anfangen?

Was mir noch einfällt:

Ich hatte vorher und jetzt auch nach dem Abändern des Scriptes folgendes aufgerufen:

Invoke-Webrequest https://prtg.mein.server.de

augerufen. Das funktionierte. Es kam eine Antwort 200 ok. Hilft das weiter?
4400667902
4400667902 16.11.2022 aktualisiert um 09:26:43 Uhr
Goto Top
Wird dem Zertifikat vertraut oder nicht? Zertifikat im CA Store vorhanden?
Wenn nicht das Cert entweder in das System importieren oder noch folgenden Code ins Skript packen (nach dem param() Block)
try{
        Add-Type '  
            using System;
            using System.Net;
            using System.Net.Security;
            using System.Security.Cryptography.X509Certificates;
            public class ServerCertificateValidationCallback
            {
                public static void Ignore()
                {
                    ServicePointManager.ServerCertificateValidationCallback += 
                        delegate
                        (
                            Object obj, 
                            X509Certificate certificate, 
                            X509Chain chain, 
                            SslPolicyErrors errors
                        )
                        {
                            return true;
                        };
                }
            }
        '  
        [ServerCertificateValidationCallback]::Ignore();
    }catch{}
4400667902
Lösung 4400667902 16.11.2022 aktualisiert um 09:37:35 Uhr
Goto Top
die Zeile
p.s. das sind mehrere Zeilen (2) die zu entfernen sind! Dann hast du wohl eine davon vergessen.

# 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"  
	try{
        Add-Type '  
            using System;
            using System.Net;
            using System.Net.Security;
            using System.Security.Cryptography.X509Certificates;
            public class ServerCertificateValidationCallback
            {
                public static void Ignore()
                {
                    ServicePointManager.ServerCertificateValidationCallback += 
                        delegate
                        (
                            Object obj, 
                            X509Certificate certificate, 
                            X509Chain chain, 
                            SslPolicyErrors errors
                        )
                        {
                            return true;
                        };
                }
            }
        '  
        [ServerCertificateValidationCallback]::Ignore();
    }catch{}
}

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 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>"  
	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
		$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 "<prtg>"  
	Write-Output "<error>1</error>"  
	Write-Output "<text>No Session Authentication Failed: $($_.Exception.Message)</text>"  
	Write-Output "</prtg>"  
	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 `
							-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 "<prtg>"  
	Write-Output "<error>1</error>"  
	Write-Output "<text>API Query Failed: $($_.Exception.Message)</text>"  
	Write-Output "</prtg>"  
	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 = '<?xml version="1.0" encoding="UTF-8" ?>  
	<prtg>
	   <result>
			<channel>TotalClients</channel>
			<value>'+($entry.'num_sta')+'</value>  
			<float>0</float>
	   </result>
	   <result>
		  <channel>Channel</channel>
		  <value>'+($entry.'channel')+'</value>  
		  <float>0</float>
	   </result>
	   <result>
		  <channel>RX-Bytes</channel>
		  <value>'+($entry.'rx_bytes') +'</value>  
		  <float>0</float>
		  <mode>Difference</mode>
		  <CustomUnit>Bytes</CustomUnit>
		</result>
		<result>
		  <channel>RX-Errors</channel>
		  <value>'+($entry.'rx_errors') +'</value>  
		  <float>0</float>
		  <mode>Difference</mode>
		  <CustomUnit>Pakete</CustomUnit>
	   </result>
		<result>
		  <channel>RX-dropped</channel>
		  <value>'+($entry.'rx_dropped') +'</value>  
		  <float>0</float>
		  <mode>Difference</mode>
		  <CustomUnit>Pakete</CustomUnit>
	   </result>
		<result>
		  <channel>TX-Bytes</channel>
		  <value>'+($entry.'tx_bytes') +'</value>  
		  <float>0</float>
		  <mode>Difference</mode>
		  <CustomUnit>Bytes</CustomUnit>
	   </result>
		<result>
		  <channel>TX-Errors</channel>
		  <value>'+($entry.'tx_errors') +'</value>  
		  <float>0</float>
		  <mode>Difference</mode>
		  <CustomUnit>Pakete</CustomUnit>
	   </result>
		<result>
		  <channel>TX-dropped</channel>
		  <value>'+($entry.'tx_dropped') +'</value>  
		  <float>0</float>
		  <mode>Difference</mode>
		  <CustomUnit>Pakete</CustomUnit>
	   </result>
	</prtg>'  
	#$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 "<?xml version="1.0" encoding="UTF-8" ?>"  
Write-Output "<prtg>"  
Write-Output "  <result>"  
Write-Output "    <channel>Clients (Total)</channel>"  
Write-Output "    <value>$($userCount)</value>"  
Write-Output "  </result>"  
Write-Output "  <result>"  
Write-Output "    <channel>Access Points Connected</channel>"  
Write-Output "    <value>$($apCount)</value>"  
Write-Output "  </result>"  
Write-Output "  <result>"  
Write-Output "    <channel>Access Points Upgradeable</channel>"  
Write-Output "    <value>$($apUpgradeable)</value>"  
Write-Output "  </result>"  
Write-Output "  <result>"  
Write-Output "    <channel>Guests</channel>"  
Write-Output "    <value>$($guestCount)</value>"  
Write-Output "  </result>"  
Write-Output "  <result>"  
Write-Output "    <channel>Load</channel>"  
Write-Output "    <value>$($jsonresult.data.sys_stats.loadavg_5)</value>"  
Write-Output "  </result>"  
Write-Output "  <result>"  
Write-Output "    <channel>Response Time</channel>"  
Write-Output "    <value>$($queryMeasurement.ElapsedMilliseconds)</value>"  
Write-Output "    <CustomUnit>msecs</CustomUnit>"  
Write-Output "  </result>"  
Write-Output "</prtg>"  

Write-Verbose "PRTG-Ubiquiti-MSXFAQ:End. Exitcode:0"  
exit 0
RalphT
RalphT 16.11.2022 um 09:42:49 Uhr
Goto Top
Ah super!

Ich hatte etwas weiter unten die zweite Zeile einfach übersehen. Jetzt läufts!
Ja dem Zertifikat wird hier vertraut. Ich habe das hier über eine interne PKI gelöst.
Jetzt ist der Sensor in PRTG auch grün.

Nochmal danke für die Hilfe!
4400667902
4400667902 16.11.2022 um 09:43:28 Uhr
Goto Top
🙂🖖