Loading...
 

Greg`s Tech blog

Nagios, NSClient++ and Powershell

Monday 13 of August, 2012
I did a talk recently at FOSSCON (cache) on how to monitor anything with Nagios. The focus of the talk was how to write NRPE checks to check obscure things in your IT environment. One of the checks I presented used a PowerShell script to check the files in a web site to ensure they hadn't changed. During development of and testing for my demo, I discovered that while my script was returning the correct errorlevel (in my case a 2), NSClient++ would only return 0 or 1.

The zero or one indicated to me that Powershell was merely reporting whether it exited normally or not.

Here is the first configuration I tried in NSClient.
[NRPE Handlers]
check_sitesign=cmd /c echo check_sitesign.ps1|powershell.exe -command -

This config, calls cmd.exe with the /c switch (run & exit), echos the script name and pipes it to powershell on STDOUT.
Powershell is executed with the -command parameter (execute the command and exit and told via the '-' to read that command from the STDIN.

After some investigation and testing from the command line it became clear the -command was an issue. The script I was passing it was seen as a single command and it either succeeded or failed hence the 0 or 1.

Next config line we tried was
[NRPE Handlers]
check_sitesign=cmd /c echo check_sitesign.ps1|powershell.exe -file -

This looked promising and tested fine on the command line but still only returned 0 or 1.

Finally, I stumbled upon this idea
[NRPE Handlers]
check_sitesign=cmd /c echo check_sitesign.ps1; exit($lastexitcode)|powershell.exe -command -

This tells Powershell to run two commands. The first runs the script and the second tells Powershell to exit with the value of the last exit code.