首页 > 其他分享 >开启并分析DNS debug日志

开启并分析DNS debug日志

时间:2023-02-02 11:57:57浏览次数:34  
标签:DNSLog Get Write Debug DNS debug 日志 match

开启DNS调试日志,记录DNS查询日志

 

 当文件达到20M后,会自动重写新日志

DNS Deug Log,使用如下脚本进行分析

脚本:

#############################################################################
# This cmdlet parses a Windows DNS Debug log. See Example uses below
#
# Revision
#       v3.0 Re-write, bug and performance fixes by Mayuresh K. <22/03/2019>
#            Tested with DNS Trace files for Windows Server 2012 R2
#            Added support for -debug switch and printing of processed stats in debug mode
#       v2.0 Adaptation (by Oscar Virot at https://gallery.technet.microsoft.com/scriptcenter/Get-DNSDebugLog-Easy-ef048bdf)
#       v1.0 Initial Version (by ASabale at https://gallery.technet.microsoft.com/scriptcenter/Read-DNS-debug-log-and-532a8504)
#
# Credits
#        ASabale - https://gallery.technet.microsoft.com/scriptcenter/Read-DNS-debug-log-and-532a8504
#        Oscar Virot - https://gallery.technet.microsoft.com/scriptcenter/Get-DNSDebugLog-Easy-ef048bdf
#############################################################################
function Get-DNSDebugLog
{
    <#
    .SYNOPSIS
    This cmdlet parses a Windows DNS Debug log.
    .DESCRIPTION
    When a DNS log is converted with this cmdlet it will be turned into objects for further parsing.
    .EXAMPLE
    Get-DNSDebugLog -DNSLog ".\Something.log" | Format-Table
    Outputs the contents of the dns debug file "Something.log" as a table.
    .EXAMPLE
    Get-DNSDebugLog -DNSLog ".\Something.log" | Export-Csv .\ProperlyFormatedLog.csv -NoTypeInformation
    Turns the debug file into a csv-file.
    .PARAMETER DNSLog
    Mandatory. Path to the DNS log or DNS log data. Allows pipelining from for example Get-ChildItem for files, and supports pipelining DNS log data.
    #>
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [String]$DNSLog
        )

    BEGIN
    {
        $DebugPreference = "Continue"
        Write-Debug "BEGIN: Initializing settings"
        #stats
        $nTotalSuccess = 0      # No of lines of interest and saved with SUCCESS
        $nTotalFailed = 0       # No of lines of interest but FAILED to save
        $nTotalDiscarded = 0    # No of lines not of interest
        $nTotalEvaluated = 0    # No of lines looked at

      #
      # data sample from Windows Server 2012 R2, used for dnspattern below
      # 2023/2/2 9:40:21 1044 PACKET  0000022E610930C0 UDP Snd 192.168.192.138 22f5 R Q [8081   DR  NOERROR] A      (6)client(3)wns(7)windows(3)com(0)
      #
       $dnspattern = "^(?<log_date>([0-9]{1,2}.[0-9]{1,2}.[0-9]{2,4}|[0-9]{2,4}.[0-9]{1,2}.[0-9]{1,2})\s*[0-9: ]{7,8}\s*(PM|AM)?) ([0-9A-Z]{3,4} PACKET\s*[0-9A-Za-z]{8,16}) (?<protocol>UDP|TCP) (?<way>Snd|Rcv) (?<ip>[0-9.]{7,15}|[0-9a-f:]{3,50})\s*([0-9a-z]{4}) (?<QR>.) (?<OpCode>.) \[.*\] (?<QueryType>.*) (?<query>\(.*)"
       $returnselect =  @{label="DateTime";expression={Get-Date -Date $match.Groups['log_date'].value.trim() -Format 'yyyy-MM-dd hh:mm:ss'}},
                        @{label="Query/Response";expression={switch($match.Groups['QR'].value.trim()){"" {'Query'};"R" {'Response'}}}},
                        @{label="Client";expression={[ipaddress] ($match.Groups['ip'].value.trim()).trim()}},
                        @{label="SendReceive";expression={$match.Groups['way'].value.trim()}},
                        @{label="Protocol";expression={$match.Groups['protocol'].value.trim()}},
                        @{label="RecordType";expression={$match.Groups['QueryType'].value.trim()}},
                        @{label="Query";expression={$match.Groups['query'].value.trim() -replace "(`\(.*)","`$1" -replace "`\(.*?`\)","." -replace "^.",""}}

        Write-Debug "BEGIN: Initializing Settings - DONE"
    }

    PROCESS
    {
        Write-Debug "PROCESS: Starting to processing File: $DNSLog"

        getDNSLogLines -DNSLog $DNSLog | % {

            # Overall Total
            $nTotalEvaluated = $nTotalEvaluated + 1
            $match = [regex]::match($_,$dnspattern) #approach 2
            if ($match.success )
            {
                Try
                {
                    $true | Select-Object $returnselect
                    $nTotalSuccess = $nTotalSuccess + 1
                    # No of lines of interest and saved with SUCCESS
                } # end try
                Catch
                {
                    # Lines of Interest but FAILED to save
                    Write-Debug "Failed to process row: $_"
                    $nTotalFailed = $nTotalFailed + 1
                } #end catch
            } #end if($match.success )
            else
            {
                # No of lines not of interest
                $nTotalDiscarded = $nTotalDiscarded + 1
            } #end else

        } # end of getDNSLogLine

        Write-Debug "PROCESS: Finished Processing File: $DNSLog"

    } # end PROCESS

    END
    {
        # print summary
        Write-Debug "Summary"
        Write-Debug "Total lines in the file ($DNSLog): $nTotalEvaluated"
        Write-Debug "Records Processed with Success: $nTotalSuccess"
        Write-Debug "Records Processed with failure: $nTotalFailed"
        Write-Debug "Records discarded as not relevant: $nTotalDiscarded"
    }

}

function getDNSLogLines
{
    Param($DNSLog)
    # Don't bother if the file does not exist
    $PathCorrect=try { Test-Path $DNSLog -ErrorAction Stop } catch { $false }

    if ($DNSLog -match "^\d\d" -AND $DNSLog -notlike "*EVENT*" -AND $PathCorrect -ne $true)
    {
        $DNSLog
    }
    elseif ($PathCorrect -eq $true)
    {
        Get-Content $DNSLog | % { $_ }
    }
}
View Code

来源于:https://github.com/maxbakhub/winposh/blob/main/Get-DNSDebugLog.ps1,修改了时间格式正则匹配及转换方式

使用方法:

Import-Module C:\Scripts\Get-DNSDebugModule.ps1
Get-DNSDebugLog C:\DNSLog\dnsquery.log

 

标签:DNSLog,Get,Write,Debug,DNS,debug,日志,match
From: https://www.cnblogs.com/dreamer-fish/p/17085531.html

相关文章

  • 图文结合带你搞懂MySQL日志之General Query Log(通用查询日志)
    GreatSQL社区原创内容未经授权不得随意使用,转载请联系小编并注明来源。GreatSQL是MySQL的国产分支版本,使用上与MySQL一致。作者:KAiTO文章来源:GreatSQL社区原创往期......
  • 如何使用Tomcat自带的日志实现tomcat-juli.jar
    前言Tomcat自带的日志实现是​​tomcat-juli.jar​​,它是对默认的JDK日志java.util.logging进行一定的封装,和标准JDK日志支持相同的配置,但是和log4j等常用的日志框架比起来......
  • DNS 是如何影响你冲浪速度的?
    本文详细介绍了DNS相关知识,包括DNS工作原理、如何提升域名解析速度、以及DNS记录与报文等内容。1.域名与域名服务器在日常上网过程中,出于好记的原因,人们更喜欢......
  • DNS
    一、DNS服务简介    DNS服务器,也称为域名解析服务器,是用来将互联网上的域名解析为IP地址的一类服务器,在世界上有成百上千台DNS服务器。对于有些公司......
  • logging模块如何实现日志文件基于时间进行分割?
    TimeRotatingFileHandler类简介基于时间来分割日志,主要用到logging.handlers模块中的TimeRotatingFileHandler类初始化参数filename:不带suffix的文件名when:......
  • 温习日志-12
    温习日志——2023年2月1日下午学习内容转换和检查数字对于数字23和23.0是相等的0.1+0.2由于JS原因不等于0.3,而是0.300000000000004将字符串转换是Number('23')......
  • mtools mongo 日志分析的利器
    mtools是一个专门用来分析mongo日志的工具基于python编写,功能还是很强大的包含的工具集mlaunch 快速构建mongo环境的工具,比较方便进行功能测试mlogfilter 进行日......
  • 通过dns api解析域名
    1.Cloudflarednsapicurl-H"accept:application/dns-json""https://1.1.1.1/dns-query?name=baidu.com"importrequestsheaders={"accept":"application/dns-......
  • 系统操作日志的实现思路
    系统操作日志的实现思路主要问题不在于写日志和表结构设计上。主要问题在识别出哪些数据做了修改。并生成日志。表中数据列众多,且要监控多个表。如果要监控的每个表都去......
  • Sql Server维护计划事务日志找不到目标数据库
     1、发现事务日志备份突然停止了  2、查看维护计划中的事务日志设置  3、发现备份任务中,事务日志需要指向的数据库不在  4、进入数据库属性5、在选项......