Thursday, September 21, 2017

Reverse CNAME lookup with dns cmdlets

In case you ever get the request to find any alias that points to a server (or list of servers), you can use the DNS commandlets to build a list of results on a zone by zone basis to further dig through.  This command will give you a rough list with 3 attributes:

Hostname = name of the dns record
ShortAlias = non-fqdn of the DNS record data (where the CNAME points to)
Alias = full DNS record data

I put the short name in there just in case the information provided to you is a short server name.

$zone = "contoso.com"
$recs = get-DnsServerResourceRecord -zonename $zone -rrtype cname |
    select @{name="shortalias"; expr={
        $_.recorddata.hostnamealias -replace "\..*",""}}, @{name="alias";
        expr={$_.recorddata.hostnamealias}},hostname

This will give you the full list of cname data for the zone in an array of objects.  If what you are searching for is an array, just run it through a loop in one of two ways [example of matching short names against an array of names to search for]

foreach ($name in $list) {  $recs | where {$_.shortalias -match $name} }

or

foreach ($entry in $recs) { if ($list -contains $entry.shortalias) { $entry } }

Its not super clean, but it will display the records.  You can modify the loops to collect the data in an array.  You could even run an extra outer loop to hit multiple zones.  The $list can just be a copy and paste into powershell from excel or whatever the list comes in.

$list = "
".split("`n")

Make sure when you paste, you don't end up with the " on a new line at the end like it shows above.  If you do that, the first loop example will dump out the whole $recs array on the last entry in $list.

If you don't have access to the Dns cmdlets, but you have rights to pull the zone with dnscmd, you can do something like this:

dnscmd /zoneprint | where {$_ -match "CNAME"} | 
  % {$resline = $_ -split "\s+"; ($resline[0], $resline[3]) }

You'll have to do something with the two values at the end, which are record name and record data.

No comments:

Post a Comment