Can I check for specific HTTP Response codes with PRTG?
Best Answer
If someone needs a Powershell variant to use with an EXE/Script Advanced sensor:
param( [string]$url = "https://www.paessler.com", [string]$timeout = "10" ) add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12' [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols $exectime = [System.Diagnostics.Stopwatch]::StartNew() $resultCode = "0" $resultLength = "0" try { $a = Invoke-WebRequest -Uri $url -TimeoutSec $timeout -UseBasicParsing -ErrorAction SilentlyContinue }catch{ if ($_.Exception.Response.StatusCode.Value__ -gt 0){ $result = $_.Exception.Response.StatusCode.Value__ $resultLength = '-1' }else{ Write-Output "<prtg>" Write-Output "<error>1</error>" Write-Output "<text>Query Failed: $($_.Exception.Message)</text>" Write-Output "</prtg>" Exit } } if ($a.StatusCode){ $result = $a.StatusCode $resultLength = $a.RawContentLength } $exectime.Stop() write-host "<prtg>" Write-Host "<result>" Write-Host "<channel>Status Code</channel>" Write-Host "<value>$($result)</value>" Write-Host "<valuelookup>prtg.standardlookups.http.statuscode</valuelookup>" Write-Host "</result>" Write-Host "<result>" Write-Host "<channel>Length</channel>" Write-Host "<value>$($resultLength)</value>" Write-Host "</result>" Write-Host "<result>" Write-Host "<channel>ExecTime</channel>" Write-Host "<value>$($exectime.ElapsedMilliseconds)</value>" Write-Host "<CustomUnit>msecs</CustomUnit>" Write-Host "</result>" write-host "<text>$($url)</text>" write-host "</prtg>"
In order to pass the url from the sensor's settings, enter it like this in the "Parameters" field:
-url 'https://www.paessler.com'
The channel displaying the return code uses an already existing lookup (prtg.standardlookups.http.statuscode) to evaluate which codes are regarded as OK/Warning/Error. Feel free to create a custom lookup based on the existing one if you need.
On a side-note: There's also another lookup called "prtg.standardlookups.http.statuscodedetailed" which contains definitions for every single return code, instead of ranges as in "prtg.standardlookups.http.statuscode".
Change Log:
- 28/07/2017 - Included a parameter for timeout. Default = 10 (seconds).
- 10/04/2018 - Added code to ignore SSL Certificate errors.
- 25/06/2018 - Modified the try/catch to properly read the status code when it is part of an exception. When this happens, the Length is reported as -1.
Created on Jan 4, 2017 7:53:50 AM by
Luciano Lingnau [Paessler]
Last change on Jun 25, 2018 7:11:48 AM by
Luciano Lingnau [Paessler]
23 Replies
There is no native Sensor within PRTG which can do this but you may use the following script in addition to a EXE/Script Sensor:
sUrl = "http://www.google.com" sStatusToCheck = 200 If Wscript.Arguments.Count = 1 then sUrl = Wscript.Arguments(0) End If If Wscript.Arguments.Count = 2 then sUrl = Wscript.Arguments(0) sStatusToCheck = Wscript.Arguments(1) End If Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0") oXMLHTTP.Open "GET", sUrl, False, " "," " oXMLHTTP.Send WScript.Echo oXMLHTTP.Status & ":" & oXMLHTTP.StatusText If oXMLHTTP.Status = sStatusToCheck then WScript.Quit("0") Else WScript.Quit("2") End If
The script can be called with parameters, where the first parameter has to be the URL and the second parameter has to be the Status Code to check for (e.g. 200,401,...).
Kudos for the script go to PRTG User Colby.
Nice script! Thnx! I extended it a bit, by disabling redirects, adding post values and extending error handling:
'************************************************ '** Init '************************************************ Option Explicit Dim oXMLHTTP Dim url, postParameter Const WinHttpRequestOption_EnableRedirects = 6 '************************************************ '** Configuration parameters '************************************************ url = "http://www.google.com" postParameter = "" '************************************************ '** Main '************************************************ If Wscript.Arguments.Count = 1 then url = Wscript.Arguments(0) ElseIf Wscript.Arguments.Count = 2 then url = Wscript.Arguments(0) postParameter = Wscript.Arguments(1) End If Set oXMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") oXMLHTTP.Option(WinHttpRequestOption_EnableRedirects) = false oXMLHTTP.Open "POST", url, False oXMLHTTP.Send postParameter '************************************************ '** Return value '************************************************ If Err.Number = 0 Then WScript.Echo oXMLHTTP.Status & ":" & oXMLHTTP.StatusText WScript.Quit(0) Else WScript.Quit(2) End If
Created on Mar 27, 2013 10:55:26 AM by
Peter Pronk
(0)
Last change on Mar 27, 2013 11:52:18 AM by
Konstantin Wolff [Paessler Support]
Here is an updated version, I believe there was a bug with Konstantin's version: when sStatusToCheck
is given as argument, it is cast as string, not int, so the status part of the script should be:
[...]
If oXMLHTTP.Status = CInt(sStatusToCheck) then
[...]
Here is a revised version (note: http only, https support should be fairly easy, or duplicate the check):
'****************************************************************************** '** Script to check a specific HTTP return code '** '** Authors: PRTG User Colby, Konstantin Wolff (Paessler Support), Thomas Blanchard - [email protected] '** Version: 0.01 '** Version Date: 2014-12-03 '** Source: '** - https://kb.paessler.com/en/topic/47373-can-i-check-for-specific-http-response-codes-with-prtg '****************************************************************************** sHost = "www.lynda.com" sStatusToCheck = 200 If Wscript.Arguments.Count = 1 then sHost = Wscript.Arguments(0) End If If Wscript.Arguments.Count = 2 then sHost = Wscript.Arguments(0) sStatusToCheck = Wscript.Arguments(1) End If sUrl = "http://" & sHost & "/" ' WScript.Echo sUrl & " " & sStatusToCheck Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0") oXMLHTTP.Open "GET", sUrl, False, " "," " oXMLHTTP.Send sMsg = sHost & " returns " & oXMLHTTP.Status & " " & oXMLHTTP.StatusText & " (expecting " & sStatusToCheck & ")" If oXMLHTTP.Status = CInt(sStatusToCheck) then WScript.Echo oXMLHTTP.Status & ":OK " & sMsg WScript.Quit("0") Else WScript.Echo oXMLHTTP.Status & ":ERROR " & sMsg WScript.Quit("2") End If
Can you please post how should parameters be typed for different url and status code? I can not get it work with parameters.
Hi Ozgur,
You can also try the following PowerShell script: http://pastebin.com/KpCSbrzt
Call it with the following parameters:
-URL "www.google.de" -ResponseCode 220 -Protocol "HTTP"
Note Remember to execute a PowerShell (x86) with admin privileges and run
Set-ExecutionPolicy RemoteSigned
...in order to make the script work :)
Hello,
I am currently running the Powershell script that Stephan posted, and the script itself is running correctly (from what I can tell). PRTG, however, is not picking up on the value that the script is putting out, and I am getting "Unauthorized access" as the last message. Any thoughts?
What URL are you trying to check?
Stephan,
I modified your version of the Powershell script (see below) so that I am able to successfully get response codes in our environment. PRTG is giving me an "Unauthorized Access" error when I tell the EXE/Script Sensor to run it. Any thoughts?
param( [string]$URL, [int]$ResponseCode1 = "", [int]$ResponseCode2 = "200", [string]$DefaultDNS = "false", [string]$protocol = "https", [string]$HeaderHost = "https://mobile.processnow.com" ) # Ignore SSL errors [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} $URL = $HeaderHost $req = [system.Net.WebRequest]::Create($URL) # Add some headers to the web request (for round robin dns and load balancers) #$req.$Host = $HeaderHost; $req.AllowAutoRedirect=$true # catch exceptions try { $res = $req.GetResponse() } catch [System.Net.WebException] { $res = $_.Exception.Response } # get the numeric response code of the request $ResponseCode1 = (($res.StatusCode) -as [int]) # and some error handling if([int]$ResponseCode1 -eq [int]$ResponseCode2){ Write-Host $ResponseCode2":Page returned HTTP code "$ResponseCode1" as expected (used "$URL")."; exit 0; } elseif([int]$ResponseCode1 -eq 200){ Write-Host $ResponseCode1":Connection error (used "$URL")."; } else{ Write-Host $ResponseCode1":Page returned "$ResponseCode1" instead of $ResponseCode2 unexpectedly (used "$URL")."; }
Created on Dec 29, 2015 7:06:19 PM by
Todd Schroeder
(0)
●1
Last change on Dec 30, 2015 8:09:31 AM by
Torsten Lindner [Paessler Support]
Can you post your sensor settings? You probably have to set "Use security context of parent device" in the sensor security context settings. Can you check that?
I have set the security settings to "Use security context of parent device." I am still getting Unauthorized Access, however I am showing that the value is 0. According to the manual, the #0 indicates that the script is running ok. Right?
Are you using a proxy server by any chance? What's the output of the script when run in PowerShell?
We do have proxies setup between the two locations.
When I run the script manually in Powershell, the output is this:
200:Page returned HTTP code 200 as expected (used https://register.processnow.com).
Is the proxy server configured via GPO? Or via IE? Can you try a different windows user in the parent device credential settings? Probably your own user account?
If someone needs a Powershell variant to use with an EXE/Script Advanced sensor:
param( [string]$url = "https://www.paessler.com", [string]$timeout = "10" ) add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12' [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols $exectime = [System.Diagnostics.Stopwatch]::StartNew() $resultCode = "0" $resultLength = "0" try { $a = Invoke-WebRequest -Uri $url -TimeoutSec $timeout -UseBasicParsing -ErrorAction SilentlyContinue }catch{ if ($_.Exception.Response.StatusCode.Value__ -gt 0){ $result = $_.Exception.Response.StatusCode.Value__ $resultLength = '-1' }else{ Write-Output "<prtg>" Write-Output "<error>1</error>" Write-Output "<text>Query Failed: $($_.Exception.Message)</text>" Write-Output "</prtg>" Exit } } if ($a.StatusCode){ $result = $a.StatusCode $resultLength = $a.RawContentLength } $exectime.Stop() write-host "<prtg>" Write-Host "<result>" Write-Host "<channel>Status Code</channel>" Write-Host "<value>$($result)</value>" Write-Host "<valuelookup>prtg.standardlookups.http.statuscode</valuelookup>" Write-Host "</result>" Write-Host "<result>" Write-Host "<channel>Length</channel>" Write-Host "<value>$($resultLength)</value>" Write-Host "</result>" Write-Host "<result>" Write-Host "<channel>ExecTime</channel>" Write-Host "<value>$($exectime.ElapsedMilliseconds)</value>" Write-Host "<CustomUnit>msecs</CustomUnit>" Write-Host "</result>" write-host "<text>$($url)</text>" write-host "</prtg>"
In order to pass the url from the sensor's settings, enter it like this in the "Parameters" field:
-url 'https://www.paessler.com'
The channel displaying the return code uses an already existing lookup (prtg.standardlookups.http.statuscode) to evaluate which codes are regarded as OK/Warning/Error. Feel free to create a custom lookup based on the existing one if you need.
On a side-note: There's also another lookup called "prtg.standardlookups.http.statuscodedetailed" which contains definitions for every single return code, instead of ranges as in "prtg.standardlookups.http.statuscode".
Change Log:
- 28/07/2017 - Included a parameter for timeout. Default = 10 (seconds).
- 10/04/2018 - Added code to ignore SSL Certificate errors.
- 25/06/2018 - Modified the try/catch to properly read the status code when it is part of an exception. When this happens, the Length is reported as -1.
Created on Jan 4, 2017 7:53:50 AM by
Luciano Lingnau [Paessler]
Last change on Jun 25, 2018 7:11:48 AM by
Luciano Lingnau [Paessler]
Hello,
How does it work with https? I have some Login-Sites which i can monitor with this script. I can open them with http and https. on one of the Server,only https is active an the other Servers will follow in time. on the Server with only https i get "Query Failed: Unable to connect to the server", wehne I use the "best Answer" script.
I really need help to monitor the https login
Hi there,
PowerShell is rather picky with its TLS connections. Kindly use the updated version in the best answer, I modified it to support self-signed certificates :)
Kind regards,
Stephan Linke, Tech Support Team
Hi, thank your for providing this script. I have a problem with the script and Windows Server 2019. I get following error when starting it with prtg: This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher. (0xD8)
Does anybody know what to change to make it work?
Thank you in advance
What do your parameters look like and did you check our guide regarding custom PowerShell based Sensors?
Created on Dec 6, 2019 12:19:10 PM by
Stephan Linke [Paessler Support]
Last change on Dec 6, 2019 12:19:16 PM by
Stephan Linke [Paessler Support]
Is the URL available without any authentication? And is that the actual URL? What error do you get?
I´ve found the issue. I had the wrong file extension (not .ps1)
@ Luciano Lingnau,
I've tried using the latest script posted but having an error on PRTG. Any thoughts?
Below is the error though i can ran the script successfully on a device.
Sensor
Custom EXE/Script Sensor
Response not well-formed: "(add-type : (0) : Source file 'C:\windows\TEMP\205ir4ea.0.cs' could not be found (1) : using System.Net; At C:\Program Files (x86)\PRTG Network Monitor\custom sensors\EXE\2_EPHD_URL_Response_Code.ps1:6 char:1 + add-type @" + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (error CS2001: S...ld not be found: CompilerError) [Add-Type], Exception + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands. AddTypeCommand add-type : (0) : No source files specified (1) : using System.Net; At C:\Program Files (x86)\PRTG Network Monitor\custom sensors\EXE\2_EPHD_URL_Response_Code.ps1:6 char:1 + add-type @" + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (warning CS2008:...files specified: CompilerError) [Add-Type], Exception + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands. AddTypeCommand add-type : Cannot add type. Compilation errors occurred. At C:\Program Files (x86)\PRTG Network Monitor\custom sensors\EXE\2_EPHD_URL_Response_Code.ps1:6 char:1 + add-type @" + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Add-Type], InvalidOperationExc eption + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.Ad dTypeCommand <prtg> <result> <channel>Status Code</channel> <value>401</value> <valuelookup>prtg.standardlookups.http.statuscodedetailed_401</valuelookup> </result> <result> <channel>Length</channel> <value>-1</value> </result> <result> <channel>ExecTime</channel> <value>58</value> <CustomUnit>msecs</CustomUnit> </result> <text>https://phd.onefluor.com/#/login</text> </prtg> )" (code: PE132)
Created on Nov 6, 2020 12:10:26 AM by
Harold Abubo
(0)
Last change on Nov 6, 2020 8:59:09 AM by
Stephan Linke [Paessler Support]
What's the output of $PSVersiontable (in PowerShell)?
Created on Nov 6, 2020 8:59:57 AM by
Stephan Linke [Paessler Support]
Last change on Nov 6, 2020 9:00:07 AM by
Stephan Linke [Paessler Support]
Please log in or register to enter your reply.
Add comment