· 6 years ago · Nov 27, 2019, 05:40 PM
1##############################################################################
2#
3# NAME: check_dns_lookup.ps1
4#
5# AUTHOR: Oliver Skibbe
6# EMAIL: oliskibbe (at) gmail.com
7#
8# COMMENT: Script to check dns lookup, should be called via NRPE/NSClient++
9#
10# Return Values for NRPE:
11# DNS answers correctly - OK (0)
12# DNS did not answer - CRITICAL (2)
13# Script errors - UNKNOWN (3)
14#
15# CHANGELOG:
16# 1.0 2015-01-21 - initial version
17#
18##############################################################################
19
20[CmdletBinding()]
21
22Param(
23 [string]$host_name,
24 [string]$dns_server
25 )
26
27Function Resolve-Dns($hostname,$dnsserver){
28 Function Get-Matches($Pattern,$groupNumber = 0) {begin { $regex = New-Object Regex($pattern) };process { foreach ($match in ($regex.Matches($_))) { ([Object[]]$match.Groups)[$groupNumber].Value }}}
29
30 # launch nslookup proc
31 $proc = New-Object System.Diagnostics.Process
32 $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo("Resolve-DnsName"," -type=A -Name $hostname -Server $dnsserver")
33 $procStartInfo.UseShellExecute = $false
34 $procStartInfo.RedirectStandardOutput = $true
35 $procStartInfo.RedirectStandardError = $true;
36 $proc.StartInfo = $procStartInfo
37 $proc.Start() | out-null
38 $proc.WaitForExit()
39
40 $sOutput = $proc.StandardOutput.ReadToEnd()
41 $eOutput = "Error: " + $proc.StandardError.ReadToEnd()
42
43 # grep for ips
44 $ips = $sOutput | Get-Matches "(?s)Name:.*Address(es)?:(.*)" 2 | Get-Matches "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" 0
45 #Write-Host $ips
46 # return
47 if ($ips.Length -gt 0) {
48 $ips
49 } else {
50 $eOutput
51 }
52}
53
54
55
56# check params
57#if ( ! ( $dns_server -As [IPAddress]) -As [Bool] ) {
58 # Write-Host "DNS-Server not a valid IP-address...exiting"
59 # exit 2
60#}
61
62#if ( ! ( $host_name ) ) {
63# Write-Host "Host-Name should not be empty..exiting"
64# exit 2
65#}
66
67# nagios return stuff
68$returnStateOK = 0
69$returnStateWarning = 1
70$returnStateCritical = 2
71$returnStateUnknown = 3
72
73
74# only at windows 2012r2 / windows 8.1
75#$dnsResult = (Resolve-DnsName -DnsOnly -Server "$ext_dns_server" -Name "$host_name" | Select-Object LastWriteTime, Name)
76
77$dnsResult = "Resolve-DnsName"
78$dnsRealResult = (& $dnsResult -Name $host_name -Server $dns_server)
79$dnsExpIP = (Resolve-DnsName $host_name -Type A -Server $dns_server).IP4Address
80# $dnsRealResult = (& $dnsResult -Name $host_name -Server $dns_server) | Select -ExpandProperty IP4Address
81
82
83
84
85
86if ( ( $dnsResult -like "Error:*" ) ) {
87 $returnString = "CRITICAL dns server " + $dns_server + ": " + $dnsResult
88 $returnState = $returnStateCritical
89} else {
90 $dnsResult = "$dnsResult"
91 $returnString = "OK: dns $dns_server and host $host_name returned $dnsExpIP"
92 $returnState = $returnStateOK
93}
94
95Write-Output $returnString
96Write-Output $dnsRealResult
97exit $returnState