This commit is contained in:
2023-07-04 12:59:44 +02:00
parent 2cef42a718
commit 09c2faad93
231 changed files with 261001 additions and 4 deletions

View File

@ -0,0 +1,119 @@
<#
.SYNOPSIS
<Overview of script>
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : 17/11/2022
Purpose/Change : <Initial script development>
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
<Example goes here. Repeat this attribute for more than one example>
.DESCRIPTION
<Brief description of script>
.PARAMETER <Parameter_Name>
<Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
<Inputs if any, otherwise state None>
.OUTPUTS
<Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
[CmdletBinding()]
Param(
[string]$action = "LockedOut",
[string]$searchBase = "",
[string]$searchScope = "Subtree",
[int]$maxWarn = 5,
[int]$maxCrit = 10
)
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "Check-AD-Account-Lock.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
Start-Transcript -Path $sLogFile -NoClobber
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#--------------------------------------------------------[Debut Du Script]---------------------------------------------------------
# check that powershell ActiveDirectory module is present
If(Get-Module -Name "ActiveDirectory" -ListAvailable) {
Try {
Import-Module -Name ActiveDirectory
}
Catch {
Write-Host "CRITICAL: Missing PowerShell ActiveDirectory module"
exit 2
}
}
Else {
Write-Host "CRITICAL: Missing PowerShell ActiveDirectory module"
exit 2
}
# check params if provided
If($action -notmatch "^(AccountDisabled|AccountExpired|AccountExpiring|AccountInactive|LockedOut|PasswordExpired|PasswordNeverExpires)$") {
Write-Host "CRITICAL: action parameter can only be AccountDisabled,AccountExpired,AccountExpiring,AccountInactive,LockedOut,PasswordExpired,PasswordNeverExpires. Provided $action"
exit 2
}
If($searchScope -notmatch "^(Base|OneLevel|Subtree)$") {
Write-Host "CRITICAL: searchScope parameter can only be Base,OneLevel,Subtree. Provided $searchScope"
exit 2
}
If(($searchBase -ne "") -and $searchBase -ne ((Get-ADDomain).DistinguishedName)) {
$search=Get-ADObject -Filter 'ObjectClass -eq "OrganizationalUnit" -and DistinguishedName -eq $searchBase'
If ($search.Count -ne 1) {
Write-Host "CRITICAL: SearchBase not found or duplicate. Provided $searchBase"
exit 2
}
}
Else {
$searchBase=(Get-ADDomain).DistinguishedName
}
$command="Search-ADAccount -"+$action+" -SearchBase '"+$searchBase+"' -SearchScope "+$searchScope
$result=invoke-expression $command
If($result.Count -gt $maxCrit) {
$state="CRITICAL"
$exitcode=2
}
Elseif($result.Count -gt $maxWarn) {
$state="WARNING"
$exitcode=1
}
Else {
$state="OK"
$exitcode=0
}
$output=$state+": "+$result.Count+" "+$action+"|"+$action+"="+$result.Count+";"+$maxWarn+";"+$maxCrit
Write-Host $output
exit $exitcode
#---------------------------------------------------------[Fin Du Script]----------------------------------------------------------
Stop-Transcript

View File

@ -0,0 +1,76 @@
<#
.SYNOPSIS
<Overview of script>
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : <Date>
Purpose/Change : <Initial script development>
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
<Example goes here. Repeat this attribute for more than one example>
.DESCRIPTION
<Brief description of script>
.PARAMETER <Parameter_Name>
<Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
<Inputs if any, otherwise state None>
.OUTPUTS
<Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
# Bibliothèques de fonctions requises
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "<script_name>.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
Start-Transcript -Path $sLogFile -NoClobber
# Initial state
$ExitCode = 0
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#--------------------------------------------------------[Debut Du Script]---------------------------------------------------------
# Get the status
$LbfoTeamMemberOutput = Get-NetLbfoTeamMember | Select-Object Name,FailureReason,Team
$LbfoTeamMemberCount = (Get-NetLbfoTeamMember).Count
# Normal state : AdministrativeDecision / NoFailure
Foreach($Member in $LbfoTeamMemberOutput) {
If(!(($Member.FailureReason -eq "NoFailure") -or ($Member.FailureReason -eq "AdministrativeDecision"))) {
$ExitCode = 2
Write-Output "CRITICAL: Member $($Member.Name) of the team $($Member.Team) state is $($Member.FailureReason)"
}
}
# Evaluate final exit code result for all passed checks.
If ($ExitCode -eq 0) {
Write-Output "OK: Members ($LbfoTeamMemberCount) of all LBFO teams are OK"
}
exit $ExitCode
#---------------------------------------------------------[Fin Du Script]----------------------------------------------------------
Stop-Transcript

99
NRPE/Check-Port-TCP.ps1 Normal file
View File

@ -0,0 +1,99 @@
<#
.SYNOPSIS
<Overview of script>
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : <Date>
Purpose/Change : <Initial script development>
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
<Example goes here. Repeat this attribute for more than one example>
.DESCRIPTION
<Brief description of script>
.PARAMETER <Parameter_Name>
<Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
<Inputs if any, otherwise state None>
.OUTPUTS
<Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[int]$PortSearch
)
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "<script_name>.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
Start-Transcript -Path $sLogFile -NoClobber
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$strCritical = ""
$strWarning = ""
$DataTexte = ""
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#--------------------------------------------------------[Debut Du Script]---------------------------------------------------------
$ListPort = Get-NetTCPConnection
Foreach ($Port in $ListPort) {
If ($Port.LocalPort -eq $PortSearch) {
$DataTexte = "Service avec $PortSearch fonctionnel"
$bReturnCritical = $False
break
}
Else {
$bReturnCritical = $TRUE
$strCritical = "Critique"
$DataTexte = "Service avec $PortSearch non fonctionnel"
}
}
If ($bReturnCritical) {
write-output $strCritical
write-output $strWarning "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output "OK" "|" $DataTexte
exit $returnStateOK
}
#---------------------------------------------------------[Fin Du Script]----------------------------------------------------------
Stop-Transcript

137
NRPE/Check-WSUS.ps1 Normal file
View File

@ -0,0 +1,137 @@
###############################################################################
# Windows PowerShell Skript to get WSUS statistics
# output readable by NRPE for Nagios monitoring
#
# FORK FROM: http://www.monitoring-portal.org/wbb/index.php?page=Thread&threadID=16424
###############################################################################
# Variables - set these to fit your needs
###############################################################################
# The server name of your WSUS server
$serverName = 'localhost'
# use SSL connection?
$useSecureConnection = $False
# the port number of your WSUS IIS website
$portNumber = 8530
# warn if a computer has not contacted the server for ... days
$daysBeforeWarn = 14
# Script - don't change anything below this line!
###############################################################################
# load WSUS framework
[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
# connect to specified WSUS server
# see here for information of the IUpdateServer class
# -> http://msdn.microsoft.com/en-us/library/microsoft.updateservices.administration.iupdateserver(VS.85).aspx
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($serverName, $useSecureConnection, $portNumber)
# get general status information
# see here for more infos about the properties of GetStatus()
# -> http://msdn.microsoft.com/en-us/library/microsoft.updateservices.administration.updateserverstatus_properties(VS.85).aspx
$status = $wsus.GetStatus()
$totalComputers = $status.ComputerTargetCount
# computers with errors
$computerTargetScope = new-object Microsoft.UpdateServices.Administration.ComputerTargetScope
$computerTargetScope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::Failed
$computersWithErrors = $wsus.GetComputerTargetCount($computerTargetScope)
# computers with needed updates
$computerTargetScope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::NotInstalled -bor [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::InstalledPendingReboot -bor [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::Downloaded
$computerTargetScope.ExcludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::Failed
$computersNeedingUpdates = $wsus.GetComputerTargetCount($computerTargetScope)
# computers without status
$computerTargetScope = new-object Microsoft.UpdateServices.Administration.ComputerTargetScope
$computerTargetScope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::Unknown
$computerTargetScope.ExcludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::Failed -bor [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::NotInstalled -bor [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::InstalledPendingReboot -bor [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::Downloaded
$computersWithoutStatus = $wsus.GetComputerTargetCount($computerTargetScope)
# computers that are OK
$computersOK = $totalComputers - $computersWithErrors - $computersNeedingUpdates - $computersWithoutStatus
# needed, but not approved updates
$updateScope = new-object Microsoft.UpdateServices.Administration.UpdateScope
$updateScope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::NotApproved
$updateServerStatus = $wsus.GetUpdateStatus($updateScope, $False)
$updatesNeededByComputersNotApproved = $updateServerStatus.UpdatesNeededByComputersCount
# computers that did not contact the server in $daysBeforeWarn days
$timeSpan = new-object TimeSpan($daysBeforeWarn, 0, 0, 0)
$computersNotContacted = $wsus.GetComputersNotContactedSinceCount([DateTime]::UtcNow.Subtract($timeSpan))
# computers in the "not assigned" group
$computerTargetScope = new-object Microsoft.UpdateServices.Administration.ComputerTargetScope
$computersNotAssigned = $wsus.GetComputerTargetGroup([Microsoft.UpdateServices.Administration.ComputerTargetGroupId]::UnassignedComputers).GetComputerTargets().Count
# output and return code
# 0: OK
# 1: WARNING
# 2: CRITICAL
# 3: UNKNOWN
$returnCode = 0
$output = ''
if ($computersNeedingUpdates -gt 0) {
$returnCode = 1
$output = "$computersNeedingUpdates PC Desactualizadas"
}
if ($computersWithErrors -gt 0) {
$returnCode = 2
if ($output -ne '') {
$output = $output + ', '
}
$output = $output + "$computersWithErrors PC Con Errores"
}
if ($computersNotContacted -gt 0) {
$returnCode = 2
if ($output -ne '') {
$output = $output + ', '
}
$output = $output + "$computersNotContacted PC Sin Contacto ($daysBeforeWarn d)"
}
if ($computersNotAssigned -gt 0) {
$returnCode = 2
if ($output -ne '') {
$output = $output + ', '
}
$output = $output + "$computersNotAssigned PC Sin Asignar"
}
if ($updatesNeededByComputersNotApproved -gt 0) {
$returnCode = 2
if ($output -ne '') {
$output = $output + ', '
}
$output = $output + "$updatesNeededByComputersNotApproved Upd. S/A"
}
if ($output -eq '') {
$output = 'Todas las Computadoras Asignadas, Activas y Al dia.'
}
$output
# append performance data
'|' + "'PC Desactualizadas'=$computersNeedingUpdates;;;0;$totalComputers"
'|' + "'PC Con Errores'=$computersWithErrors;"
"'PC Sin Estatus'=$computersWithoutStatus;"
"'PC OK'=$computersOK;"
$host.SetShouldExit($returnCode)
exit $returnCode

101
NRPE/Check_Certificats.ps1 Normal file
View File

@ -0,0 +1,101 @@
<#
.SYNOPSIS
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : 16/11/2022
Purpose/Change :
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
.DESCRIPTION
.PARAMETER <Parameter_Name>
.INPUTS
.OUTPUTS
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
# Bibliothèques de fonctions requises
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "<script_name>.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
$Folder = "C:\TradeXpress5\users\ediprod\ssl\certs"
$ListCert = dir $Folder -Include *.cer, *.crt, *.cert -Recurse
$dtCurrent = Get-Date
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$nWarning = 60
$nCritical = 30
$strCritical = ""
$strWarning = ""
$DataTexte = ""
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#------------------------------------------------------------[Script]--------------------------------------------------------------
cls
Foreach ($Certificate in $ListCert) {
$objCertificate = New-Object Security.Cryptography.X509Certificates.X509Certificate2 $Certificate.FullName
$dtRemain = $objCertificate.NotAfter - $dtCurrent
$nRemainDays = $dtRemain.Days
$DataTexte += "'"+$Certificate.name+"'="+$nRemainDays+" "
If ($nRemainDays -lt 0) {
$strCritical = $strCritical + "EXPIRED " + $objCertificate.SubjectName.Name.ToString() + " expired " + $objCertificate.NotAfter.ToString() + "`n"
$bReturnCritical = $TRUE
}
Elseif ( $nRemainDays -lt $nCritical) {
$strCritical = $strCritical + "Critical " + $objCertificate.SubjectName.Name.ToString() + " expires " + $objCertificate.NotAfter.ToString() + "`n"
$bReturnCritical = $TRUE
}
Elseif ( $nRemainDays -lt $nWarning) {
$strWarning = $strWarning + "Warning " + $objCertificate.SubjectName.Name.ToString() + " expires " + $objCertificate.NotAfter.ToString() + "`n"
$bReturnWarning = $TRUE
}
Else {
#Nothing for now
}
}
If ($bReturnCritical) {
write-output $strCritical
write-output $strWarning "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output "OK" "|" $DataTexte
exit $returnStateOK
}

View File

@ -0,0 +1,83 @@
<#
.SYNOPSIS
<Overview of script>
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : <Date>
Purpose/Change : <Initial script development>
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
<Example goes here. Repeat this attribute for more than one example>
.DESCRIPTION
<Brief description of script>
.PARAMETER <Parameter_Name>
<Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
<Inputs if any, otherwise state None>
.OUTPUTS
<Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
# Bibliothèques de fonctions requises
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "<script_name>.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
## ReturnStates
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$Separateur = ":"
$DataTexte = ""
$str = ""
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#------------------------------------------------------------[Script]--------------------------------------------------------------
cls
cd "C:\Program Files\Centreon NSClient++"
$ValiableRetour = cmd /c nscp.exe sys -- --validate Microsoft --all
Foreach ($ligne in $ValiableRetour) {
If ($ligne.StartsWith("\Microsoft Dynamics AX Object Server")) {
$ArrayA = $ligne.Split("\")
$ArrayB = ($ArrayA[2]).Split($Separateur)
#Write-Host $ArrayB[0]
#Write-Host ($ArrayB[1].Substring(0,$ArrayB[1].Length-1)).substring(4)
$DataTexte += "'"+$ArrayB[0]+"'="+($ArrayB[1].Substring(0,$ArrayB[1].Length-1)).substring(4)+" "
If ($ArrayB[0] -eq "ACTIVE SESSIONS") {
$str = "Nombre de sessions active : "+($ArrayB[1].Substring(0,$ArrayB[1].Length-1)).substring(4)
}
}
}
write-output "OK - $str" "|" $DataTexte
exit $returnStateOK

View File

@ -0,0 +1,181 @@
<#
.SYNOPSIS
Check Windows disks fragmentation status.
.DESCRIPTION
Check Windows disks fragmentation status.
Optionally performs defragmentation.
.OUTPUTS
OK: All disk fragmentation status is ok.
WARNING: % of fragmentation equal to Warning treshold.
CRITICAL: % of fragmentation equal to Critical treshold.
.PARAMETER warning
% of fragmentation for warning treshold.
Default System default.
.PARAMETER critical
% of fragmentation for critical treshold.
Default None.
.PARAMETER disks
Disks to check fragmentation status.
Default: all.
Example: "C:","D:","F:"
.PARAMETER defrag
Defrag disks if warning or critical.
Default: false
.PARAMETER forceDefrag
Defrag disks if free space is low.
Default: false
.EXAMPLE
Only checks all drives with system default warning treshold.
check_diskdefragstatus.ps1
.EXAMPLE
Checks all drives with 15 warning treshold and 40 critical treshold.
check_diskdefragstatus.ps1 -warning 15 -critical 40
.EXAMPLE
Checks only C and D drives with system default warning treshold and 50 critical treshold.
check_diskdefragstatus.ps1 -disks "C:","D:" -critical 50
.EXAMPLE
Checks C drive with system default warning treshold.
If defragmentation status is greater than warning or critical treshold, it runs disk defragmentation.
check_diskdefragstatus.ps1 -disks "C:" -defrag
.EXAMPLE
Checks C drive with system default warning treshold.
If defragmentation status is greater than warning or critical treshold, it runs disk defragmentation even C: disk free space is low.
check_diskdefragstatus.ps1 -disks "C:" -defrag -forceDefrag
.NOTES
Author: Juan Granados
#>
Param(
[Parameter(Mandatory = $false, Position = 0)]
[ValidateRange(0, 100)]
[int]$warning = 0,
[Parameter(Mandatory = $false, Position = 1)]
[ValidateRange(0, 100)]
[int]$critical = 0,
[Parameter(Mandatory = $false, Position = 2)]
[ValidateNotNullOrEmpty()]
[string[]]$disks = "all",
[Parameter()]
[switch]$defrag,
[Parameter()]
[switch]$forceDefrag
)
#Requires -RunAsAdministrator
$ErrorActionPreference = "Stop"
$global:nagiosStatus = 0
$global:nagiosOutput = ""
Function Defrag-Disk($diskToDefrag) {
If ($forceDefrag) {
Write-Verbose "Forcing $($diskToDefrag.DriveLetter) defragmentation"
$result = $diskToDefrag.Defrag($true)
}
Else {
Write-Verbose "Performing $($diskToDefrag.DriveLetter) defragmentation"
$result = $diskToDefrag.Defrag($false)
}
If ($result.ReturnValue -eq 0) {
Write-Verbose "Defragmentation successful"
Write-Verbose "Current fragmentation is $($result.DefragAnalysis.FilePercentFragmentation)"
$diskToDefrag.DefragResult = $result
If (($critical -gt 0) -and ($result.DefragAnalysis.FilePercentFragmentation -gt $critical)) {
Write-Verbose "Status is critical"
$global:nagiosStatus = 2
}
Elseif (($warning -eq 0 -and $result.DefragAnalysis.FilePercentFragmentation -gt 10) -or ( ($warning -gt 0) -and ($result.DefragAnalysis.FilePercentFragmentation -gt $warning))) {
Write-Verbose "Status is warning"
$global:nagiosStatus = 1
}
}
Else {
Write-Output "CRITICAL: Error $($result.ReturnValue) defragmenting drive $($diskToDefrag.DriveLetter)"
Write-Output "Check error codes: https://docs.microsoft.com/en-us/previous-versions/windows/desktop/vdswmi/defrag-method-in-class-win32-volume"
Exit(2)
}
$global:nagiosOutput += "Disk $($diskToDefrag.DriveLetter) fragmentation is $($result.DefragAnalysis.FilePercentFragmentation)."
}
Try {
If ($disks -eq "all") {
$drives = get-wmiobject win32_volume | Where-Object { $_.DriveType -eq 3 -and $_.DriveLetter -and (Get-WMIObject Win32_LogicalDiskToPartition | Select-Object Dependent) -match $_.DriveLetter }
}
Else {
Foreach ($disk in $disks) {
If (-not ($disk -match '[A-Za-z]:')) {
Write-Output "UNKNOWN: Error $($drive) is not a valid disk unit. Expected N:, where N is drive unit. Example C: or D: or F:"
Exit(3)
}
}
$drives = get-wmiobject win32_volume | Where-Object { $_.DriveType -eq 3 -and $_.DriveLetter -in $disks }
}
If (-not ($drives)) {
Write-Output "UNKNOWN: No drives found with get-wmiobject win32_volume command"
Exit(3)
}
Foreach ($drive in $drives) {
Write-Verbose "Analizing drive $($drive.DriveLetter)"
$result = $drive.DefragAnalysis()
If ($result.ReturnValue -eq 0) {
Write-Verbose "Current fragmentation is $($result.DefragAnalysis.FilePercentFragmentation)"
$drive | Add-Member -NotePropertyName 'DefragResult' -NotePropertyValue $result
If (($critical -gt 0) -and ($result.DefragAnalysis.FilePercentFragmentation -gt $critical)) {
If (-not $defrag) {
Write-Verbose "Disk will not be defragmented. Status is critical"
$global:nagiosStatus = 2
}
Else {
Defrag-Disk -diskToDefrag $drive
Continue
}
}
Elseif (($warning -eq 0 -and $result.DefragRecommended -eq "True") -or ( ($warning -gt 0) -and ($result.DefragAnalysis.FilePercentFragmentation -gt $warning))) {
If (-not $defrag) {
Write-Verbose "Disk will not be defragmented. Status is warning"
$global:nagiosStatus = 1
}
Else {
Defrag-Disk -diskToDefrag $drive
Continue
}
}
$global:nagiosOutput += "Disk $($drive.DriveLetter) fragmentation is $($result.DefragAnalysis.FilePercentFragmentation)."
}
Else {
Write-Output "CRITICAL: Error $($result.ReturnValue) checking status of drive $($drive.DriveLetter)"
Write-Output "Check error codes: https://docs.microsoft.com/en-us/previous-versions/windows/desktop/vdswmi/defraganalysis-method-in-class-win32-volume#return-value"
Exit(2)
}
}
}
Catch {
Write-Output "CRITICAL: $($_.Exception.Message)"
Exit(2)
}
$global:nagiosOutput += " |"
If ($critical -eq 0) {
$critical = 50;
}
If ($warning -eq 0) {
$warning = 10;
}
Foreach ($drive in $drives) {
$global:nagiosOutput += " $($drive.DriveLetter.TrimEnd(':'))=$($drive.DefragResult.DefragAnalysis.FilePercentFragmentation)%;$($warning);$($critical);0;100"
}
If ($global:nagiosStatus -eq 2) {
Write-Output "CRITICAL: $($global:nagiosOutput)"
Exit(2)
}
Elseif ($global:nagiosStatus -eq 1) {
Write-Output "WARNING: $($global:nagiosOutput)"
Exit(1)
}
Else {
Write-Output "OK: disk fragmentation is correct.$($global:nagiosOutput)"
Exit(0)
}

View File

@ -0,0 +1,69 @@
<#
Ester Niclos Ferreras
OK UP
WARNING
CRITICAL Stopped
UNKNOWN not found
#>
#
# Shell arguments
#
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$ApplicationPool
)
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$DataTexte = ""
$strCritical = ""
$strWarning = ""
[System.Reflection.Assembly]::LoadFrom( "C:\windows\system32\inetsrv\Microsoft.Web.Administration.dll" ) > $null
$servermanager = [Microsoft.Web.Administration.ServerManager]::OpenRemote("localhost")
$apppools = $servermanager.ApplicationPools["$ApplicationPool"]
$iis = Get-ItemProperty HKLM:\SOFTWARE\Microsoft\InetStp\ | select setupstring
# Nagios output
$resultstring='IISPOOL UNKNOWN ' + $ApplicationPool + ' ' + $status +' ; ' + $iis.SETUPSTRING + ' '
$exit_code = $UNKNOWN
If ($apppools -ne $null) {
$status = $apppools.state
If ($status -eq 'Started') {
$str = 'OK '+ $ApplicationPool + ' ' + $status +' ; ' + $iis.SETUPSTRING + ' '
}
Else {
$strCritica = 'CRITICAL '+ $ApplicationPool + ' ' + $status +' ; ' + $iis.SETUPSTRING + ' '
$bReturnCritical = $TRUE
}
}
If ($bReturnCritical) {
write-output $strCritica "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output $str "|" $DataTexte
exit $returnStateOK
}

View File

@ -0,0 +1,77 @@
<#
Ester Niclos Ferreras
Returns nomber of web site connections
UNKNOWN - not found
OK - connections
warning - current connections greater than warning value
critical - current connection greater than critical value
#>
#
# Shell arguments
#
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$website,
[Parameter(Mandatory=$True,Position=2)]
[int]$warning_value,
[Parameter(Mandatory=$True,Position=3)]
[int]$critical_value
)
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$DataTexte = ""
$strCritical = ""
$strWarning = ""
$counter = Get-Counter "\Service Web($website)\connexions actives"
# Nagios output
$resultstring='CONNECTIONS UNKNOWN ' + $website + ' not found'
$exit_code = $UNKNOWN
If ($counter -ne $null) {
$connections=$counter.CounterSamples.CookedValue
If ($connections -gt $critical_value) {
$strCritica = 'CONNECTIONS CRITICAL '+ $website +' connections '+ $connections
$bReturnCritical = $TRUE
}
Elseif ($connections -gt $warning_value) {
$strWarning = 'CONNECTIONS WARNING '+ $website +' connections '+ $connections
$bReturnWarning = $TRUE
}
Else {
$str= 'CONNECTIONS OK '+ $website +' connections '+ $connections
}
$DataTexte = "connections=" + $connections + ';' + $warning_value + ';' + $critical_value + "; "
}
If ($bReturnCritical) {
write-output $strCritica "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output $str "|" $DataTexte
exit $returnStateOK
}

75
NRPE/Check_iis8_site.ps1 Normal file
View File

@ -0,0 +1,75 @@
<#
Ester Niclos Ferreras
Checks IIS Site state
OK - started
CRITICAL - STOPPED
UNKNOWN - not found
#>
#
# Shell arguments
#
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$website
)
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$DataTexte = ""
$strCritical = ""
$strWarning = ""
[System.Reflection.Assembly]::LoadFrom( "C:\windows\system32\inetsrv\Microsoft.Web.Administration.dll" ) > $null
$servermanager = [Microsoft.Web.Administration.ServerManager]::OpenRemote("localhost")
$site = $servermanager.Sites["$website"]
$iis = Get-ItemProperty HKLM:\SOFTWARE\Microsoft\InetStp\ | select setupstring
# Nagios output
$resultstring="IISSITE UNKNOWN $website not found"
$exit_code = $UNKNOWN
If ($site -ne $null) {
$status= $site.State
If ($status -eq "Started") {
$str = 'OK ' + $website + ' ' + $status + '-' + $iis.setupstring
}
Elseif ($status -eq $null) {
$strWarning = "UNKNOWN $website exists, but has no state. Check it is not a FTP site."
$bReturnWarning = $TRUE
}
Else {
$strCritical = 'CRITICAL '+ $website + ' ' + $status + '-' + $iis.setupstring
$bReturnCritical = $TRUE
}
}
If ($bReturnCritical) {
write-output $strCritica "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output $str "|" $DataTexte
exit $returnStateOK
}

View File

@ -0,0 +1,95 @@
##################################################################################
#
# NAME: check_win_last_update.ps1
#
# AUTHOR: Peter Luetke-Bexten
# COAUTHOR: Christoph Hamschmidt
# EMAIL: peter.luetke-bexten (at) benteler.com
#
# COMMENT:
# Script to calculate the Days since last Windows Update
# which is understandable for every Manager :-}
# should be called via NRPE/NSClient++
# inspired by bratislav.stojkovic@gmail.com check_win_lastupdate.vbs
# but with using Microsoft.Update.Session instead of Registry.
# Registry query not working in W2016 or W10.
#
# NSCLIENT.ini:
# check_win_lastupdate = cmd /c echo scriptspowershellcheck_win_last_update.ps1 $ARG1$ $ARG2$ ; exit($lastexitcode) | "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -noninteractive -noprofile -ExecutionPolicy unrestricted -command -
#
# NRPE Check:
# check_nrpe -H targethost -p 5666 -t 120 -u -c check_win_lastupdate -a 35 70
#
# CHANGELOG:
# 1.0 20180126 - initial version
#
################################################################################
# Script calculates curent date and date of last Windows Update Installation
## Arguments
#$wldays = $args[0]
#$cldays = $args[1]
$wldays = 90
$cldays = 180
## ReturnStates
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
## Get lasat installed update and select date as object
$Session = New-Object -ComObject Microsoft.Update.Session
$Searcher = $Session.CreateUpdateSearcher()
$HistoryCount = $Searcher.GetTotalHistoryCount()
## http://msdn.microsoft.com/en-us/library/windows/desktop/aa386532%28v=vs.85%29.aspx
$DatelastInstall = $Searcher.QueryHistory(0,$HistoryCount) | ForEach-Object {$_} | Select-Object -First 1 | Select-Object -Property Date
## Get actual date
$Datenow = Get-Date
## Get number of days since list install
$DayslastInstall = ($Datenow - $DatelastInstall.date).Days
$DayslastInstalldate = ($Datenow.Date - $DatelastInstall.Date).Days
## Debug
# $DatelastInstall.ToString()
# $DatelastInstall
# $DatelastInstall.date
# $Datenow
# $Datenow.date
# $DayslastInstall
# $DayslastInstalldate
If (!$wldays) {
echo "Usage: check_win_last_update.ps1 "
exit 3
}
# if ($DayslastInstall) {
If ($DayslastInstalldate -eq 0) {
Write-Host "OK - Patches applied $DayslastInstalldate days ago at $($DatelastInstall.Date)"
exit $returnStateOK
}
Elseif ($DayslastInstall -lt $wldays) {
Write-Host "OK - Patches applied $DayslastInstalldate days ago at $($DatelastInstall.Date)"
exit $returnStateOK
}
Elseif ($DayslastInstall -lt $cldays) {
Write-Host "WARNING - Patches applied $DayslastInstalldate days ago $($DatelastInstall.Date)"
exit $returnStateWarning
}
Elseif ($DayslastInstall -gt $cldays) {
Write-Host "CRITICAL - Patches applied $DayslastInstalldate days ago $($DatelastInstall.Date)"
exit $returnStateCritical
}
Else {
Write-Host "UNKNOWN"
exit $returnStateUnknown
}
# } else {
else {
Write-Host "UNKNOWN - unable to get date of last Widows Update Installation"
exit $returnStateUnknown
}

View File

@ -0,0 +1,52 @@
# This is a little basic script I have written to query a WSUS server
# about the updates needed by the system.
#
# It will only return a Critical status if there are any Critical Security Updates,
# or Critical Updates waiting to be applied.
#
# I by no mean pretend to be a profesionnal scripter, so feel free
# to modify as you see fit!
#
# Written by: Alexandre Beauclair
# Date: April 12th 2012
#Declaring base variables. You can change the $wsusserver value if needed.
$wsusserver = "localhost"
$securityCritical = 0
$criticalUpdates = 0
#Load required assemblies
[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
#Create necessary objects
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($wsusserver,$False)
$updatescope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
#Specify we are looking for updates which are Not Approved, and Not Installed.
$updatescope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::NotApproved
$updatescope.IncludedInstallationStates = [Microsoft.UpdateServices.Administration.UpdateInstallationStates]::NotInstalled
#Find how many updates are available.
$checkSecurityCritical = $wsus.GetUpdates($updatescope) | where {$_.UpdateClassificationTitle -eq "Security Updates"} | ft MsrcSeverity -AutoSize | FIND /c " Critical"
$checkCriticalUpdates = $wsus.GetUpdates($updatescope) | where {$_.UpdateClassificationTitle -eq "Critical Updates"} | ft UpdateClassificationTitle | FIND /c "Critical Updates"
$securityCritical += $checkSecurityCritical
$criticalUpdates += $checkCriticalUpdates
#Return message and exit code accordingly.
if(($securityCritical -gt 0) -or ($criticalUpdates -gt 0)){
Write-Host "CRITICAL - There are updates waiting to be applied. Critical Updates: $criticalUpdates Critical Security Updates: $securityCritical"
exit 2
}else{
Write-Host "OK - There are no critical updates waiting to be applied."
exit 0
}

78
NRPE/README.md Normal file
View File

@ -0,0 +1,78 @@
## Addon NRPE
- Tout les sondes ci-dessous son à ajouter dans le fichier nsclient.ini
- Recherche la rubrique : `[/settings/external scripts/scripts]`
## Partie Supervision :
- <u>Certificats-local.ps1</u> <br>
**Description** : Controle l'expiration d'un ou plusieurs certificat se trouvant dansle même dossier. <br>
Check_ca=cmd /c echo C:\Exploit\Centreon\Certificats-local.ps1 | powershell.exe -command -
- <u>Check_win_last_update.ps1</u> <br>
**Description** :
Check_win_last_update=cmd /c echo C:\Exploit\Centreon\check_win_last_update.ps1 | powershell.exe -command -
- <u>WSTester.ps1</u> <br>
**Description** :
Check_WSTester=cmd /c echo C:\Exploit\Centreon\WSTester.ps1 | powershell.exe -command -
- <u>Dynamics-AX.ps1</u> <br>
**Description** : Pour l'application Dynamics AX
Check_DynamicsAX=cmd /c echo C:\Exploit\Centreon\Dynamics-AX.ps1 | powershell.exe -command -
- <u>Check-NetLbfoTeamMember.ps1</u> <br>
**Description** :
Check_TeamMember=cmd /c echo C:\Exploit\Centreon\Check-NetLbfoTeamMember.ps1 | powershell.exe -command -
- <u>Check_diskdefragstatus.ps1</u> <br>
**Description** :
Check_Defrag=cmd /c echo C:\Exploit\Centreon\check_diskdefragstatus.ps1 -warning 15 -critical 30 | powershell.exe -command -
- <u>Check_iis.ps1</u> <br>
**Description** :
Check_IIS=cmd /c echo C:\Exploit\Centreon\check_iis.ps1 | powershell.exe -command -
- <u>Check_IISPerformance_State.ps1</u> <br>
**Description** :
Check_iisperformance_state=cmd /c echo C:\Exploit\Centreon\Check_IISPerformance_State.ps1 -WebSite $ARG1$ | powershell.exe -command -
- <u>Check_iis8_app_pool_state.ps1</u> <br>
**Description** :
Check_IIS8_AppPool=cmd /c echo C:\Exploit\Centreon\check_iis8_app_pool_state.ps1 $ARG1$ | powershell.exe -command -
- <u>Check_iis8_connections.ps1</u> <br>
**Description** :
Check_IIS8_Connexions=cmd /c echo C:\Exploit\Centreon\check_iis8_connections.ps1 $ARG1$ $ARG2$ $ARG3$ | powershell.exe -command -
- <u>Check_iis8_site.ps1</u> <br>
**Description** :
Check_IIS8_SiteWeb=cmd /c echo C:\Exploit\Centreon\check_iis8_site.ps1 $ARG1$ | powershell.exe -command -
## Partie Hypervision :
- <u>Task-kill-Process.ps1</u> <br>
**Description** : Permet de couper un process si une alerte définie est atteinte
Task_Kill_Process=cmd /c echo C:\Exploit\Centreon\Task-kill-Process.ps1 $ARG1$ | powershell.exe -command -
- <u>Task-Restart-Service.ps1</u> <br>
**Description** : Relance d'un service
Task_Restart_Service=cmd /c echo C:\Exploit\Centreon\Task-Restart-Service.ps1 $ARG1$ | powershell.exe -command -
- <u>Task-Defrag.ps1</u> <br>
**Description** : Lance une défragmentation en cas d'alerte
Task_Defrag=cmd /c echo C:\Exploit\Centreon\Task_defrag.ps1 | powershell.exe -command -

54
NRPE/Task-Defrag.ps1 Normal file
View File

@ -0,0 +1,54 @@
<#
.SYNOPSIS
<Overview of script>
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : 18/11/2022
Purpose/Change : <Initial script development>
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
<Example goes here. Repeat this attribute for more than one example>
.DESCRIPTION
<Brief description of script>
.PARAMETER <Parameter_Name>
<Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
<Inputs if any, otherwise state None>
.OUTPUTS
<Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "Task-Defrag.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
Start-Transcript -Path $sLogFile -NoClobber
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#------------------------------------------------------------[Script]--------------------------------------------------------------
defrag /C
#---------------------------------------------------------[Fin Du Script]----------------------------------------------------------
Stop-Transcript

View File

@ -0,0 +1,60 @@
<#
.SYNOPSIS
<Overview of script>
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : 18/11/2022
Purpose/Change :
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
<Example goes here. Repeat this attribute for more than one example>
.DESCRIPTION
<Brief description of script>
.PARAMETER <Parameter_Name>
<Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
<Inputs if any, otherwise state None>
.OUTPUTS
<Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[int]$ProcessKill
)
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "Task-Kill-Process.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
Start-Transcript -Path $sLogFile -NoClobber
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#------------------------------------------------------------[Script]--------------------------------------------------------------
taskkill /im $ProcessKill /f
#---------------------------------------------------------[Fin Du Script]----------------------------------------------------------
Stop-Transcript

View File

@ -0,0 +1,72 @@
<#
.SYNOPSIS
<Overview of script>
.NOTES
Version : 1.0
Author : Hubert CORNET
Creation Date : <Date>
Purpose/Change : <Initial script development>
.LINK
https://www.tips-of-mine.fr
.EXEMPLE
<Example goes here. Repeat this attribute for more than one example>
.DESCRIPTION
<Brief description of script>
.PARAMETER <Parameter_Name>
<Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
<Inputs if any, otherwise state None>
.OUTPUTS
<Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[int]$ServiceName
)
# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"
#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "Task-Restart-Service.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName
Start-Transcript -Path $sLogFile -NoClobber
#-----------------------------------------------------------[Functions]------------------------------------------------------------
#------------------------------------------------------------[Script]--------------------------------------------------------------
Foreach ($Service in $ServiceName) {
Restart-Service $ServiceName -ErrorAction SilentlyContinue -ErrorVariable ServiceError
If (!$ServiceError) {
$Time=Get-Date
Write-Host "Redémarrage du service $Service à $Time"
}
If ($ServiceError) {
write-host $error[0]
exit 3
}
}
#---------------------------------------------------------[Fin Du Script]----------------------------------------------------------
Stop-Transcript

View File

@ -0,0 +1,61 @@
Function QuerySQLServer([string]$DBServer, [string]$DBName, [string]$Query) {
Try {
$ErrorActionPreference = "Stop"
$resultsDataTable = New-Object System.Data.DataTable
$cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
$cn.open()
$cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
$reader = $cmd.ExecuteReader()
$resultsDataTable.Load($reader)
$cn.Close()
return $resultsDataTable
}
Catch {
write-host $_.Exception.Message
$_.Exception.Message >> "d:\error.log"
}
Finally {
$ErrorActionPreference = "Continue"
}
}
cls
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$strCritical = ""
$strWarning = ""
$DataTexte = ""
$ComputerName = $env:COMPUTERNAME
$Liste = QuerySQLServer "$ComputerName" "dhb_prd" "SELECT A.session_id, Db_Name(database_id) AS [database], DateDiff(MINUTE, A.connect_time, GetDate()) AS [Connected (mins)], num_reads, num_writes, login_name, Text AS SQL FROM sys.dm_exec_connections AS A INNER JOIN sys.dm_exec_sessions AS B ON A.session_id = B.session_id INNER JOIN sys.sysprocesses AS s ON s.spid = A.session_id OUTER APPLY::fn_get_sql(sql_handle)"
$Liste | Format-Table | Out-String|% {Write-Host $_}
$DataTexte = $Liste.login_name
If ($bReturnCritical) {
write-output $strCritical
write-output $strWarning "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output "OK - Nombre de requete en cours : $DataTexte | 'NbrequetesEnCours'=$DataTexte "
exit $returnStateOK
}

View File

@ -0,0 +1,62 @@
Function QuerySQLServer([string]$DBServer, [string]$DBName, [string]$Query) {
Try {
$ErrorActionPreference = "Stop"
$resultsDataTable = New-Object System.Data.DataTable
$cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
$cn.open()
$cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
$reader = $cmd.ExecuteReader()
$resultsDataTable.Load($reader)
$cn.Close()
return $resultsDataTable
}
Catch {
write-host $_.Exception.Message
$_.Exception.Message >> "d:\error.log"
}
Finally {
$ErrorActionPreference = "Continue"
}
}
cls
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$strCritical = ""
$strWarning = ""
$DataTexte = ""
$ComputerName = $env:COMPUTERNAME
$Liste = QuerySQLServer "$ComputerName" "dhb_prd" "SELECT wait_type ,wait_time_ms ,CONVERT(DECIMAL(7,4),100.0 * wait_time_ms/SUM(wait_time_ms) OVER()) AS wait_percent FROM sys.dm_os_wait_stats WHERE wait_type NOT IN ('CLR_SEMAPHORE','LAZYWRITER_SLEEP','RESOURCE_QUEUE','SLEEP_TASK' ,'SLEEP_SYSTEMTASK','SQLTRACE_BUFFER_FLUSH','WAITFOR', 'LOGMGR_QUEUE','CHECKPOINT_QUEUE' ,'REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TO_FLUSH','BROKER_TASK_STOP', 'CLR_MANUAL_EVENT','CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT', 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN')" # -- filtrage de quelques types d'attente ORDER BY wait_percent DESC GO"
$Liste | Format-Table | Out-String|% {Write-Host $_}
pause
$DataTexte = $Liste.waiting_tasks_count+$Liste.wait_time_ms+$Liste.max_wait_time_ms+$Liste.signal_wait_time_ms
If ($bReturnCritical) {
write-output $strCritical
write-output $strWarning "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output "OK - Nombre de requete en cours : $DataTexte | 'NbrequetesEnCours'=$DataTexte "
exit $returnStateOK
}

View File

@ -0,0 +1,60 @@
Function QuerySQLServer([string]$DBServer, [string]$DBName, [string]$Query) {
Try {
$ErrorActionPreference = "Stop"
$resultsDataTable = New-Object System.Data.DataTable
$cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
$cn.open()
$cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
$reader = $cmd.ExecuteReader()
$resultsDataTable.Load($reader)
$cn.Close()
return $resultsDataTable
}
Catch {
write-host $_.Exception.Message
$_.Exception.Message >> "d:\error.log"
}
Finally {
$ErrorActionPreference = "Continue"
}
}
cls
$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
$strCritical = ""
$strWarning = ""
$DataTexte = ""
$ComputerName = $env:COMPUTERNAME
$Liste = QuerySQLServer "$ComputerName" "dhb_prd" "SELECT count(r.session_id) as NbrequetesEnCours FROM sys.dm_exec_requests r join sys.dm_exec_sessions ses on ses.session_id = r.session_id CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS p"
$DataTexte = $Liste.NbrequetesEnCours
If ($bReturnCritical) {
write-output $strCritical
write-output $strWarning "|" $DataTexte
exit $returnStateCritical
}
Elseif ($bReturnWarning) {
write-output $strWarning "|" $DataTexte
exit $returnStateWarning
}
Else {
write-output "OK - Nombre de requete en cours : $DataTexte | 'NbrequetesEnCours'=$DataTexte "
exit $returnStateOK
}

View File

@ -0,0 +1,211 @@
# Script name: check_veeam_endpoint_eventlogs.ps1
# Version: 1.0
# Created on: 1May2016
# Author: Dallas Haselhorst
# Purpose: Check Veeam Endpoint Backup success or failure via event logs
#
# Note: This is for monitoring Endpoint. Veeam Endpoint only allows for a single
# job. If multiple jobs must be monitored, there is a separate script called
# check_veeam_eventlogs.ps1 also found on Nagios Exchange
#
# Note: does NOT use PowerShell plug-in
#
# Copyright:
# 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 &lt;http://www.gnu.org/licenses/&gt;.
#
# For Nagios XI NCPA usage, the following line should be copied to the $ARG1$ text box
# -t '&lt;token&gt;' -P &lt;port number&gt; -M 'agent/plugin/check_veeam_endpoint_eventlogs.ps1/&lt;ArgBackupJobName&gt;/&lt;ArgLastHours&gt;
#
# For testing from the Nagios command line, add './check_ncpa.py -H &lt;IP address&gt;' to the above line
# ArgBackupJobName is required.
# ArgLastMinutes should be populated with the time to check in minutes, e.g. 60 (for 1 hour), 120 (for 2 hours),
#
# Examples
# -t 'TokenPass' -P 5693 -M 'agent/plugin/check_veeam_endpoint_eventlogs.ps1/24'
# -- above line would check the last 24 hours of Veeam Endpoint Backup logs
# Pull in arguments
$ArgLogName = "Veeam Agent" # veeam backup event log
$ArgEntryType = 1,2,3,4 # look for critical, error, warning and informational logs
$ArgProviderName = "Veeam Agent"
$ArgEventID = 190 # backup job complete event id
$ArgLastHours = $args[0]
# Setting default values if null
if (!$ArgLastHours) { $ArgLastHours = (24) }
if (!$ArgWarningTH) { $ArgWarningTH = 0 }
if (!$ArgCriticalTH) { $ArgCriticalTH = 0 }
if (!$ArgMaxEntries) { $ArgMaxEntries = 50 }
$CriticalErrorResultCount = 0
$WarningResultCount = 0
$InfoResultCount = 0
$EventTypeLoopCount = 0
$LogNameLoopCount = 0
$ProviderNameLoopCount = 0
$EventIDLoopCount = 0
$Properties='Level','Message','ProviderName','TimeCreated','Id'
$Filter = @{
LogName = $ArgLogName
StartTime = (Get-Date).AddHours(-$ArgLastHours)
}
if($ArgProviderName) { $Filter += @{ProviderName = $ArgProviderName } }
if($ArgEventID) { $Filter += @{Id = $ArgEventID } }
if($ArgEntryType) { $Filter += @{Level = $ArgEntryType } }
# -ea SilentlyContinue gets rid of non-terminating error resulting from zero events
$LogEntries = Get-WinEvent -MaxEvents $ArgMaxEntries -FilterHashtable $Filter -ea SilentlyContinue -Oldest | Select-Object -Property $Properties
if ($LogEntries) {
ForEach ($LogEntry in $LogEntries) {
if ($LogEntry.Message.ToString() -like "*Veeam Agent*")
{
$Level=$LogEntry.Level.ToString()
if (($Level -eq 1) -Or ($Level -eq 2)) # find critical and errors
{
$Message=$LogEntry.Message.Substring(0,[System.Math]::Min(180, $LogEntry.Message.Length)).TrimEnd().ToString()
$ProviderName=$LogEntry.ProviderName.ToString()
$TimeCreated=$LogEntry.TimeCreated.ToString()
$Id=$LogEntry.Id.ToString()
$CriticalErrorResultCount++
$CriticalErrorResults=@"
At: $TimeCreated
Level: $Level
Event ID: $Id
Message: $Message
Source: $ProviderName
$CriticalErrorResults
"@
}
elseif ($Level -eq 3) # find warnings
{
$Message=$LogEntry.Message.Substring(0,[System.Math]::Min(180, $LogEntry.Message.Length)).TrimEnd().ToString()
$ProviderName=$LogEntry.ProviderName.ToString()
$TimeCreated=$LogEntry.TimeCreated.ToString()
$Id=$LogEntry.Id.ToString()
$WarningResultCount++
$WarningResults=@"
At: $TimeCreated
Level: $Level
Event ID: $Id
Message: $Message
Source: $ProviderName
$WarningResults
"@
}
else # all that's left, find info (4) messages
{
$Message=$LogEntry.Message.Substring(0,[System.Math]::Min(180, $LogEntry.Message.Length)).TrimEnd().ToString()
$ProviderName=$LogEntry.ProviderName.ToString()
$TimeCreated=$LogEntry.TimeCreated.ToString()
$Id=$LogEntry.Id.ToString()
$InfoResultCount++
$InfoResults=@"
At: $TimeCreated
Level: $Level
Event ID: $Id
Message: $Message
Source: $ProviderName
$InfoResults
"@
}
}
}
}
$Results= @"
$CriticalErrorResults $WarningResults $InfoResults
"@
if ($ArgEntryType) {
$TypeArray = @("all level","critical","error","warning","informational")
$LevelString = foreach ($Entry in $ArgEntryType) {
if ($ArgEntryType.Count -gt 1) {
$LevelStringBuild = $TypeArray[$Entry]
if ($ArgEntryType.Count -ne $EventTypeLoopCount+1) {
$LevelStringBuild +=","
}
}
else { $LevelStringBuild = $TypeArray[$Entry] }
$EventTypeLoopCount++
$LevelStringBuild
}
}
$LogNameString = foreach ($LogNameEntry in $ArgLogName) {
$LogNameStringBuild += $LogNameEntry
if ($ArgLogName.Count -gt 1 -And $ArgLogName.Count -ne $LogNameLoopCount+1) {
$LogNameStringBuild += ", "
}
$LogNameLoopCount++
}
$ProviderNameString = foreach ($ProviderNameEntry in $ArgProviderName) {
$ProviderNameStringBuild += $ProviderNameEntry
if ($ArgProviderName.Count -gt 1 -And $ArgProviderName.Count -ne $ProviderNameLoopCount+1) {
$ProviderNameStringBuild += ", "
}
$ProviderNameLoopCount++
}
$EventIDString = foreach ($EventIDEntry in $ArgEventID) {
$EventIDStringBuild += "$EventIDEntry"
if ($ArgEventID.Count -gt 1 -And $ArgEventID.Count -ne $EventIDLoopCount+1) {
$EventIDStringBuild += ", "
}
$EventIDLoopCount++
}
If ($CriticalErrorResultCount -gt 0) {
$ResultString += "Backup failed: $CriticalErrorResultCount critical error(s) for backup job in last $ArgLastHours hours "
$NagiosMetricString += "'Errors'=$CriticalErrorResultCount 'BackupUnknown'=1 "
$ExitCode = 1
}
If ($WarningResultCount -gt 0) {
$ResultString += "Warning: backup job had $WarningResultCount warning message(s) in the last $ArgLastHours hours "
If ($ExitCode -ne 1) {
$NagiosMetricString += "'BackupUnknown'=1 "
$ExitCode = 1
}
$NagiosMetricString += "'Warnings'=$WarningResultCount "
}
If (($InfoResultCount -lt 1) -And ($ExitCode -ne 1)) {
$ResultString += "Backup failed: backup job has not run in last $ArgLastHours hours "
$NagiosMetricString += "'BackupNotRun'=1 "
If ($ExitCode -ne 1) { $ExitCode = 1 }
}
If (($InfoResultCount -ge 1) -And ($CriticalErrorResultCount -eq 0 ) -And ($WarningResultCount -eq 0 )){
$ResultString += "OK: backup job completed successfully in last $ArgLastHours hours "
$NagiosMetricString = "'BackupSuccess'=1 "
$ExitCode = 0
}
write-host $ResultString
write-host $Results
write-host $ResultString"|"$NagiosMetricString
exit $ExitCode

View File

@ -0,0 +1,173 @@
#################################################################################
#
# 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, ck@tupel7.de
#
# 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