Windows Update Check

This support forum board is for support questions relating to Nagios XI, our flagship commercial network monitoring solution.
Locked
smetzler
Posts: 27
Joined: Mon Apr 15, 2019 11:06 am

Windows Update Check

Post by smetzler »

Hello,

I am hoping someone can help me with locating a script to allow Nagios to monitor servers for Windows Updates. I have researched the forums and downloaded several (at least 3 or 4) scripts which have been installed correctly in Nagios and within the nsclient\script directory. I have followed all of the instructions to modify the ini file and to restart the service yet I am unable to get Nagios to come back with a response. Just today I have tried a visual basic script, windows script and powershell. All three work on the remote sever just fine and return the results however, when I utilize the check_nrpe check command nothing is returned. One of the remote servers I tried had several updates ready to be installed so I know there are updates waiting. I am running Nagios XI 5.6.14 and NSClient 5.2.35 for x64. I had the script (powershell) working in the past but since the latest update two weeks ago the script is no longer working. I have verified Nagios does not have any updates which have not been applied.

Thank you for your time!

Shane Metzler, MSCy, GCFE
User avatar
jbrunkow
Posts: 441
Joined: Fri Mar 13, 2020 10:45 am

Re: Windows Update Check

Post by jbrunkow »

Can you please specify exactly which instructions you followed, and which scripts you are trying to run?

How are you running the check_nrpe script? If you are doing it from the terminal, you may want to use the -v flag to gather more verbose output that could help us understand why it is failing.
As of May 25th, 2018, all communications with Nagios Enterprises and its employees are covered under our new Privacy Policy.

Be sure to check out our Knowledgebase for helpful articles and solutions!
smetzler
Posts: 27
Joined: Mon Apr 15, 2019 11:06 am

Re: Windows Update Check

Post by smetzler »

Hello,

The following code is check_updates.wsf. The code works on the server but nagios does not return a value:

Code: Select all

<job>
  <script language="VBScript">
    
    Set objShell = CreateObject("WScript.Shell")

    Dim sysroot
    sysroot = objShell.ExpandEnvironmentStrings("%systemroot%")

    Set objExec = objShell.Exec("cmd.exe /c type " & sysroot & "\SoftwareDistribution\ReportingEvents.log")
    results = LCase(objExec.StdOut.ReadAll)

    res_split = Split(results, vbCrLf)

    Dim regEx
    Set regEx = New RegExp
    regEx.Pattern = "(.)\S*\s*\S*\s*\S*\s*\d\s*(\d*)\s*\S*\s*\S*[0-9\s]*\S*\s*\S*\s*.*\t(.*)"
    regEx.IgnoreCase = true

    count = 1
    ReDim arrDyn(1)

    For Each zeile in res_split

      firstsign = regEx.Replace(zeile, "$1")

      If (firstsign = "{") Then

      	number = regEx.Replace(zeile, "$2")
        finish = regEx.Replace(zeile, "$3")

      	If (number = 147) Then

          count = count + 1
          ReDim Preserve arrDyn(count + 1)
	  arrDyn(count + 1) = finish
        End If

      End If

    Next

    mount_updates = -1

    For x = 0 to UBound(arrDyn)

      If x = UBound(arrDyn) Then
	      end_array = Split(arrDyn(x), " ")
	      mount_updates = end_array(UBound(end_array) - 1)
      End If

    Next

    Set objSysInfo = CreateObject("Microsoft.Update.SystemInfo")
    If objSysInfo.RebootRequired Then

      reboot = " Reboot required!"
      status = 1 
     
    Else

      reboot = " No Reboot required!"
      status = 0

    End If

    If mount_updates > 0 Then

      If mount_updates = 1 Then

        Wscript.echo("Warning: 1 Update detected!" & reboot)
        status = 1

      ElseIf mount_updates >= 2 Then
	
        Wscript.echo("Critical: " & mount_updates & " Updates detected!" & reboot)
        status = 2

      End If
   
    Else

      Wscript.echo("OK, 0 Updates detected!" & reboot)

    End If

    Wscript.Quit(status)
   
  </script>
</job>
The other code I tried is check_windows_update.ps1:

Code: Select all

#################################################################################
#
# NAME: 	check_windows_updates.ps1
#
# COMMENT:  Script to check for windows updates with Nagios + NRPE/NSClient++
#
#           Checks:
#           - how many critical and optional updates are available 
#           - whether the system is waiting for reboot after installed updates 
#
#           Features:
#           - properly handles NRPE's 1024b limitation in return packet
#           - configurable return states for pending reboot and optional updates
#           - performance data in return packet shows titles of available critical updates
#           - caches updates in file to reduce network traffic, also dramatically increases script execution speed
#
#			Return Values for NRPE:
#			No updates available - OK (0)
#			Only Hidden Updates - OK (0)
#			Updates already installed, reboot required - WARNING (1)
#			Optional updates available - WARNING (1)
#			Critical updates available - CRITICAL (2)
#			Script errors - UNKNOWN (3)
#
#			NRPE Handler to use with NSClient++:
#			[NRPE Handlers]
#			check_updates=cmd /c echo scripts\check_windows_updates.ps1 $ARG1$ $ARG2$; exit $LastExitCode | powershell.exe -command - 
#
#
# IMPORTANT: 	Please make absolutely sure that your Powershell ExecutionPolicy is set to Remotesigned.
#				Also note that there are two versions of powershell on a 64bit OS! Depending on the architecture 
#				of your NSClient++ version you have to choose the right one:
#
#				64bit NSClient++ (installed under C:\Program Files ):
#				%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe "Set-ExecutionPolicy RemoteSigned"
#
#				32bit NSClient++ (installed under C:\Program Files (x86) ):
#				%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe "Set-ExecutionPolicy RemoteSigned"
#
#
# CHANGELOG:
# 1.45 2016-08-05 - corrected some typos, added newline after each critical update
# 1.44 2016-04-05 - performance data added
# 1.42 2015-07-20 - strip unwanted characters from returnString
# 1.41 2015-04-24 - removed wuauclt /detectnow if updates available
# 1.4  2015-01-14 - configurable return state for pending reboot
# 1.3  2013-01-04 - configurable return state for optional updates
# 1.2  2011-08-11 - cache updates, periodically update cache file
# 1.1  2011-05-11 - hidden updates only -> state OK
#				  - call wuauctl.exe to show available updates to user
# 1.0  2011-05-10 - initial version
#
#################################################################################
# Copyright (C) 2011-2015 Christian Kaufmann, [email protected]
#
# This program is free software; you can redistribute it and/or modify it under 
# the terms of the GNU General Public License as published by the Free Software 
# Foundation; either version 3 of the License, or (at your option) any later 
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT 
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with 
# this program; if not, see <http://www.gnu.org/licenses>.
#################################################################################

$htReplace = New-Object hashtable
foreach ($letter in (Write-Output ä ae ö oe ü ue Ä Ae Ö Oe Ü Ue ß ss)) {
    $foreach.MoveNext() | Out-Null
    $htReplace.$letter = $foreach.Current
}
$pattern = "[$(-join $htReplace.Keys)]"

$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$returnStatePendingReboot = $returnStateWarning
$returnStateOptionalUpdates = $returnStateWarning

$updateCacheFile = "check_windows_updates-cache.xml"
$updateCacheExpireHours = "24"

$logFile = "check_windows_update.log"

function LogLine(	[String]$logFile = $(Throw 'LogLine:$logFile unspecified'), 
					[String]$row = $(Throw 'LogLine:$row unspecified')) {
	$logDateTime = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
	Add-Content -Encoding UTF8 $logFile ($logDateTime + " - " + $row) 
}

if (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"){ 
	Write-Host "updates installed, reboot required"
	if (Test-Path $logFile) {
		Remove-Item $logFile | Out-Null
	}
	if (Test-Path $updateCacheFile) {
		Remove-Item $updateCacheFile | Out-Null
	}
	exit $returnStatePendingReboot
}

if (-not (Test-Path $updateCacheFile)) {
	LogLine -logFile $logFile -row ("$updateCacheFile not found, creating....")
	$updateSession = new-object -com "Microsoft.Update.Session"
	$updates=$updateSession.CreateupdateSearcher().Search(("IsInstalled=0 and Type='Software'")).Updates
	Export-Clixml -InputObject $updates -Encoding UTF8 -Path $updateCacheFile
}

if ((Get-Date) -gt ((Get-Item $updateCacheFile).LastWriteTime.AddHours($updateCacheExpireHours))) {
	LogLine -logFile $logFile -row ("update cache expired, updating....")
	$updateSession = new-object -com "Microsoft.Update.Session"
	$updates=$updateSession.CreateupdateSearcher().Search(("IsInstalled=0 and Type='Software'")).Updates
	Export-Clixml -InputObject $updates -Encoding UTF8 -Path $updateCacheFile
} else {
	LogLine -logFile $logFile -row ("using valid cache file....")
	$updates = Import-Clixml $updateCacheFile
}

$criticalTitles = "";
$countCritical = 0;
$countOptional = 0;
$countHidden = 0;

if ($updates.Count -eq 0) {
	Write-Host "OK - no pending updates.|critical=$countCritical;optional=$countOptional;hidden=$countHidden"
	exit $returnStateOK
}

foreach ($update in $updates) {
	if ($update.IsHidden) {
		$countHidden++
	}
	elseif ($update.AutoSelectOnWebSites) {
		$criticalTitles += $update.Title + " `n"
		$countCritical++
	} else {
		$countOptional++
	}
}
if (($countCritical + $countOptional) -gt 0) {
	$returnString = "Updates: $countCritical critical, $countOptional optional" + [Environment]::NewLine + "$criticalTitles"
	$returnString = [regex]::Replace($returnString, $pattern, { $htReplace[$args[0].value] })
	
	# 1024 chars max, reserving 48 chars for performance data -> 
	if ($returnString.length -gt 976) {
        Write-Host ($returnString.SubString(0,975) + "|critical=$countCritical;optional=$countOptional;hidden=$countHidden")
    } else {
        Write-Host ($returnString + "|critical=$countCritical;optional=$countOptional;hidden=$countHidden")
    }   
}

#if ($countCritical -gt 0 -or $countOptional -gt 0) {
#	Start-Process "wuauclt.exe" -ArgumentList "/detectnow" -WindowStyle Hidden
#}

if ($countCritical -gt 0) {
	exit $returnStateCritical
}

if ($countOptional -gt 0) {
	exit $returnStateOptionalUpdates
}

if ($countHidden -gt 0) {
	Write-Host "OK - $countHidden hidden updates.|critical=$countCritical;optional=$countOptional;hidden=$countHidden"
	exit $returnStateOK
}

Write-Host "UNKNOWN script state"
exit $returnStateUnknown
Again the code works fine when executed on the server. I have tried both from the SSH console and the GUI for Nagios and both do not return any value.

Thank you,

Shane Metzler, MSCy, GCFE
User avatar
jbrunkow
Posts: 441
Joined: Fri Mar 13, 2020 10:45 am

Re: Windows Update Check

Post by jbrunkow »

Thankyou for posting your scripts. I will stage a test using the same ones to see if I encounter the same problem.

Please give us a little time to examine the code, as pinpointing these problems can sometimes be tedious.
As of May 25th, 2018, all communications with Nagios Enterprises and its employees are covered under our new Privacy Policy.

Be sure to check out our Knowledgebase for helpful articles and solutions!
User avatar
jbrunkow
Posts: 441
Joined: Fri Mar 13, 2020 10:45 am

Re: Windows Update Check

Post by jbrunkow »

The next think I would do is try to determine if there is a more general issue afflicting any of the machines involved. Are you able to run any scripts at all using the check_nrpe script?

You mentioned that you had this script working at some point. What has changed since then? Do you have backups running so that you could just revert the machine back to that point?

Are these the scripts that you downloaded? If so, have you modified them at all?

check_updates.wsf = https://exchange.nagios.org/directory/P ... s)/details

check_windows_update.ps1 = https://exchange.nagios.org/directory/P ... ll/details

I have not had a problem running these scripts. I should probably also mention that the software offered on the Nagios Exchange is not directly supported by us.
As of May 25th, 2018, all communications with Nagios Enterprises and its employees are covered under our new Privacy Policy.

Be sure to check out our Knowledgebase for helpful articles and solutions!
smetzler
Posts: 27
Joined: Mon Apr 15, 2019 11:06 am

Re: Windows Update Check

Post by smetzler »

Hello,

I have other scripts on the servers which utilize check_nrpe. I have not modified the code at all and yes that is where I downloaded the files from. I am fine with not using the scripts and utilizing a supported method from Nagios if you have a suggestion on how we can monitor servers for Windows Updates.

Thank you,
User avatar
jbrunkow
Posts: 441
Joined: Fri Mar 13, 2020 10:45 am

Re: Windows Update Check

Post by jbrunkow »

NSClient++ is not developed by us, so it is not directly supported. We encourage the use of NCPA to ensure compatibility with XI and unify components across platforms.

However, even with that you would need something to bridge the gap between our interface and the operating system using a script or plugin. I believe there are several ways to get the systems to communicate over WMI or possibly even Windows counters.

It is possible that we could reach out to the developer of either of these plugins to notify them about the problems we are encountering. They may have more insight into the problem, or they could be unaware that there is a bug in their script.
As of May 25th, 2018, all communications with Nagios Enterprises and its employees are covered under our new Privacy Policy.

Be sure to check out our Knowledgebase for helpful articles and solutions!
User avatar
jbrunkow
Posts: 441
Joined: Fri Mar 13, 2020 10:45 am

Re: Windows Update Check

Post by jbrunkow »

I am sorry I didn't come across this earlier! Have you tried the check_windows plugin?
https://exchange.nagios.org/directory/P ... ll/details

Please refer to the following document for more information.
https://assets.nagios.com/downloads/nag ... ios-XI.pdf
As of May 25th, 2018, all communications with Nagios Enterprises and its employees are covered under our new Privacy Policy.

Be sure to check out our Knowledgebase for helpful articles and solutions!
smetzler
Posts: 27
Joined: Mon Apr 15, 2019 11:06 am

Re: Windows Update Check

Post by smetzler »

Thank you so much. I am going to look over the check_windows plugin now.

Shane
User avatar
jbrunkow
Posts: 441
Joined: Fri Mar 13, 2020 10:45 am

Re: Windows Update Check

Post by jbrunkow »

Excellent! Please let us know if that suits your needs.
As of May 25th, 2018, all communications with Nagios Enterprises and its employees are covered under our new Privacy Policy.

Be sure to check out our Knowledgebase for helpful articles and solutions!
Locked