Microsoft MVP성태의 닷넷 이야기
Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [링크 복사], [링크+제목 복사]
조회: 11966
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 6개 있습니다.)
.NET Framework: 221. Cache 영향을 받지 않는 DNS 이름 풀이
; https://www.sysnet.pe.kr/2/0/1069

.NET Framework: 264. 다중 LAN 카드 환경에서 Dns.GetHostAddresses(local)가 반환해 주는 IP의 우선순위는 어떻게 될까요?
; https://www.sysnet.pe.kr/2/0/1169

Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회
; https://www.sysnet.pe.kr/2/0/11795

개발 환경 구성: 434. 존재하지 않는 IP 주소에 대한 Dns.GetHostByAddress/gethostbyaddr/GetNameInfoW 실행이 느리다면?
; https://www.sysnet.pe.kr/2/0/11852

개발 환경 구성: 435. 존재하지 않는 IP 주소에 대한 Dns.GetHostByAddress/gethostbyaddr/GetNameInfoW 실행이 느리다면? - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/11853

개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
; https://www.sysnet.pe.kr/2/0/13089




PowerShell - Zone 별로 DNS 레코드 유형 정보 조회

아래와 같은 글이 있군요. ^^

Extract DNS Records to CSV with PowerShell
; https://chentiangemalc.wordpress.com/2018/10/17/extract-dns-records-to-csv-with-powershell/

github를 통해 공개한 스크립트를 보면,

Get-AllDnsResourceRecords.ps1
; https://github.com/chentiangemalc/PowerShellScripts/blob/master/Get-AllDnsResourceRecords.ps1

[CmdletBinding()]
param(
[Parameter(Position=0)]
[String]$DNSServer)

$Zones = @(Get-DnsServerZone -ComputerName $DNSServer)
$Data = @() 
ForEach ($Zone in $Zones) {
    ($Zone | Get-DnsServerResourceRecord -ComputerName $DNSServer) | `
        Select-Object -Property `
            @{Label="Zone Name";expression={( $Zone.ZoneName )}},`
            DistinguishedName,`
            HostName,`
            RecordClass,`
            RecordType,`
            Timestamp,`
            TimeToLive,`
            @{label="Data";expression={
                $r = $_.RecordData
                switch ($_.RecordType)
                {
                    "A" { $r.IPv4Address.IPAddressToString }
                    "NS" { $r.NameServer }
                    "SOA" { 
                        "ExpireLimit=$($r.ExpireLimit);"+
                        "MinimumTimeToLive=$($r.MinimumTimeToLive);"+
                        "PrimaryServer=$($r.PrimaryServer);"+
                        "RefreshInterval=$($r.RefreshInterval);"+
                        "ResponsiblePerson=$($r.ResponsiblePerson);"+
                        "RetryDelay=$($r.RetryDelay);"+
                        "SerialNumber=$($r.SerialNumber)"

                    }
                    "CNAME" {  $r.HostNameAlias }
                    "SRV"{ 
                        "DomainName=$($r.DomainName);"+
                        "Port=$($r.Port);"+
                        "Priority=$($r.Priority);"+
                        "Weight=$($r.Weight)"
                    }
                    "AAAA" { $r.IPv6Address.IPAddressToString }
                    "PTR" { $r.PtrDomainName } 
                    "MX" {
                        "MailExchange=$($r.MailExchange);"+
                        "Prefreence=$($r.Preference)"
                    }
                    "TXT" { $r.DescriptiveText }
                    Default { "Unsupported Record Type" }
                }}
            }
}

다운로드해 다음과 같이 실행할 수 있습니다.

& "c:\temp\ps_dns.ps1" -DnsServer 8.8.8.8

그런데 실제로 실행해 보면 이런 오류가 발생합니다.

PS C:\temp> & "C:\temp\ps_dns.ps1" -DnsServer 8.8.8.8
Get-DnsServerZone : Failed to enumerate zones from the server 8.8.8.8.
At C:\temp\ps_dns.ps1:44 char:12
+ $Zones = @(Get-DnsServerZone -ComputerName $DNSServer)
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (8.8.8.8:root/Microsoft/...S_DnsServerZone) [Get-DnsServerZone], CimException
    + FullyQualifiedErrorId : WIN32 1722,Get-DnsServerZone

Win32 에러 코드가 1722면 "The RPC server is unavailable"입니다. 그러니까, 해당 글의 예제와는 달리 구글 쪽의 DNS 서버 조회는 할 수 없는 것입니다. (실제로 에러 메시지를 보면 "8.8.8.8:root/Microsoft/...S_DnsServerZone"이라는 마이크로소프트 쪽 Namespace 정보가 나옵니다.)

따라서 위의 명령은 Microsoft DNS 서버의 정보를 알아내는데 사용할 수 있습니다. 아래는 그에 대한 출력 예제입니다.

PS C:\Users> $ScriptBlockContent =
    {
        $myArg = 'mydnsserver'
        C:\temp\ps_dns.ps1 -DNSServer $myArg
    }

PS C:\Users> Invoke-Command -ScriptBlock $ScriptBlockContent

Zone Name         : _msdcs.testad.com
DistinguishedName : DC=@,DC=_msdcs.testad.com,cn=MicrosoftDNS,DC=ForestDnsZones,DC=testad,DC=com
HostName          : @
RecordClass       : IN
RecordType        : NS
Timestamp         :
TimeToLive        : 01:00:00
Data              : testpdc.testad.com.

Zone Name         : _msdcs.testad.com
DistinguishedName : DC=@,DC=_msdcs.testad.com,cn=MicrosoftDNS,DC=ForestDnsZones,DC=testad,DC=com
HostName          : @
RecordClass       : IN
RecordType        : NS
Timestamp         :
TimeToLive        : 01:00:00
Data              : testpdc4.testad.com.

...[생략]...

Zone Name         : testad.com
DistinguishedName : DC=@,DC=testad.com,cn=MicrosoftDNS,DC=DomainDnsZones,DC=testad,DC=com
HostName          : @
RecordClass       : IN
RecordType        : NS
Timestamp         :
TimeToLive        : 01:00:00
Data              : testpdc4.testad.com.

Zone Name         : testad.com
DistinguishedName : DC=@,DC=testad.com,cn=MicrosoftDNS,DC=DomainDnsZones,DC=testad,DC=com
HostName          : @
RecordClass       : IN
RecordType        : NS
Timestamp         :
TimeToLive        : 01:00:00
Data              : testpdc.testad.com.

...[생략]...




참고로, 본문의 스크립트에서 사용한 Get-DnsServerZone 명령어 자체가 실행이 안 되는 경우가 많을 것입니다.

PS C:\Users> Get-DnsServerZone
Get-DnsServerZone : The term 'Get-DnsServerZone' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-DnsServerZone
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-DnsServerZone:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

이런 경우, dnsserver 모듈을 import 해 보면 다음과 같은 결과가 나옵니다.

PS C:\Users> Import-Module dnsserver
Import-Module : The specified module 'dnsserver' was not loaded because no valid module file was found in any module directory.
At line:1 char:1
+ Import-Module dnsserver
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (dnsserver:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

"Extract DNS Records to CSV with PowerShell" 글의 덧글에 보면 Windows 10과 Server 2016에 내장되어 있다고 하는데 실제로는 DNS 관련 구성 요소가 설치된 경우에만 유효합니다. 설치 방법은, 다음과 같이 "Add Roles and Features Wizard"에서 "Remote Server Administration Tools" / "Role AdministrationTools" 범주에 있는 "DNS Server Tools"를 선택, 설치하면 됩니다.

dns_server_tools_1.png

참고로 윈도우 10에는 이에 해당하는 구성 요소가 없습니다. 대신 별도로 다음의 링크에서 다운로드할 수 있습니다.

Remote Server Administration Tools for Windows 10 
; https://www.microsoft.com/en-us/download/details.aspx?id=45520

주의할 것은, 위의 링크에서 제공하는 RSAT은 Windows 10의 1709, 1803 버전 용입니다. 이번에 릴리스한 1807 버전의 경우 다음의 경고문에 써진 것처럼,

IMPORTANT: Starting with Windows 10 October 2018 Update, RSAT is included as a set of "Features on Demand" in Windows 10 itself. See "Install Instructions" below for details, and "Additional Information" for recommendations and troubleshooting. RSAT lets IT admins manage Windows Server roles and features from a Windows 10 PC.


"Settings" / "Apps & features" / "Manage optional features" 패널에서 "Add a feature" 버튼을 통해 다음과 같이 개별 RSAT 구성 요소를 설치할 수 있습니다.

dns_server_tools_2.png




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 12/19/2018]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2019-04-24 01시21분
정성태

1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241557닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241563닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241641닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241618닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241632닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241545닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241606닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241617오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241630오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241478닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241644디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241644오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241742닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241746디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242623오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241819닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241619Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241952닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241708VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241735닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241685닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242016닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...