Scott Daniels

DHCP Scope Check

Here’s a Powershell script you can use with Sensu (or Nagios?) to monitor DHCP scopes. To help ensure you have few spare IP addresses to hand out. The moaning never ends when you run out.
The script will request all DHCP scopes, and check the percentage used. You can define a warning and critical percentage.

Defaults:
-server localhost
-w 80% returns a warning
-c 90% returns critical

/etc/sensu/plugins/check_dhcp.ps1


param ( [string]$server = localhost,
        [int]$warn = 80,
        [int]$crit= 90
)

try {

    foreach($scope in (Get-DhcpServerv4Scope -ComputerName $server)) {
    
        if(Get-DhcpServerv4ScopeStatistics -ComputerName $server -ScopeId $scope.ScopeId | where {$_.PercentageInUse -gt $warn }) {
            #Exit with a warning if more than 80 percent in use.
            write-host "WARNING:" $scope.ScopeId "("$scope.Name") has" (Get-DhcpServerv4ScopeStatistics -ComputerName eroaddc02 -ScopeId $scope.ScopeId | Select-Object -Expand Free) "IP(s) available."
            $warning = $warnalarm+1 #exit 2
    
        } elseif(Get-DhcpServerv4ScopeStatistics -ComputerName $server -ScopeId $scope.ScopeId | where {$_.PercentageInUse -gt $crit}) {
            #Exit with a critical if more than 90 percent in use.
            write-host "CRITICAL:" $scope.ScopeId "("$scope.Name") has" (Get-DhcpServerv4ScopeStatistics -ComputerName eroaddc02 -ScopeId $scope.ScopeId | Select-Object -Expand Free) "IP(s) available."
            $crit = $warnalarm+1 #exit 1
        } else { 
            # All scopes are OK.
            write-host "OK" $scope.ScopeId "("$scope.Name") has" (Get-DhcpServerv4ScopeStatistics -ComputerName eroaddc02 -ScopeId $scope.ScopeId | Select-Object -Expand Free) "IP(s) available."
        }

    }

    if($crit) { 
        write-host "$critalarm Critical(s)"
        exit 2 
    }
    if($warning) { 
        write-host "$warnalarm Warning(s)"
        exit 1 
    }
    write-host "All OK"
    exit 0
}

Catch [System.Exception] {
    Write-Host "Could not get DHCP information or script exception found."
    exit 3 
}

Example Sensu Check

/etc/sensu/conf.d/check_dhcp.conf


"checks": {
    "dhcp_scope": {
      "handlers": ["default","email"],
      "command": "/etc/sensu/plugins/check_dhcp.ps1 -server :::name::: -warn 60 -crit 90",
      "standalone": false,
      "interval": 60,
      "subscribers": ["dhcp"]
    }
}