PowerShell: NSG Flow Log parsen

Zwar bietet Azure mit Log Analytics bereits alle Mittel um entsprechende Logs zu analysieren und auszuwerten. Anders sieht es jedoch aus, wenn die Logs nur im exportieren JSON Format vorliegen, weil diese etwa mittels Storage Browser heruntergeladen und bereitgestellt wurden.

Um die NSF Flow Logs komfortabel analysieren zu können, habe ich mit PowerShell einen kleinen Parser geschrieben. Das Script wertet die Datei aus, bereitet die Records zwecks besserer Lesbarkeit in tabellarischer Form auf und bietet optional die Möglichkeit bestimmte Daten in eine separate CSV-Datei zu extrahieren.

Drei Variablen müssen vor Start des Scripts definiert werden. Der Quellpfad in dem die JSON Dateien liegen, der Exportpfad in die optionale CSV Datei ausgegeben werden soll und das Zeitformat des Timestamps.

Den passenden Artikel zu den NSG Flow logs gibt es unter folgendem Link. Dort sind unteranderem auch Beispiele der Log Dateien.

https://learn.microsoft.com/en-us/azure/network-watcher/network-watcher-nsg-flow-logging-overview

Hinweis: Die angegebenen Ordner werden auf Existenz geprüft. Sollte ein Ordner nicht gefunden werden können, wird das Script beendet.

# IT-Feed NSG Flow Log Parser v 0.1

# Set source, destination path and datetime format
$ImportFolderJSON = "E:\json"
$ExportFolderCSV = "$env:Temp"
$DateTimeFormat = "dd.MM.yyyy HH:mm:ss"

#############################################################

# Check if folders exists
$Folders = @(
    $ImportFolderJSON,
    $ExportFolderCSV
)

foreach ($Folder in $Folders) {
    if (!(Test-Path -Path $Folder -PathType Container)) {
        Write-Host "The folder '$Folder' does not exist."
        pause
        exit
    }
}


# Create an empty array to store the output
$output = @()

# Get all the JSON files in the folder and loop through each file
Get-ChildItem -Path $ImportFolderJSON -Filter *.json -Recurse | ForEach-Object {
    # Import the JSON file and convert it to a JSON object
    $json = Get-Content -Path $_.FullName | ConvertFrom-Json

    # Loop through each record in the JSON file
    foreach ($record in $json.records) {
        # Loop through each flow in the record
        foreach ($flow in $record.properties.flows) {
            # Loop through each flow tuple in the flow
            foreach ($tuple in $flow.flows.flowTuples) {
                # Split the flow tuple into its components
                $tupleComponents = $tuple.Split(",")

                # Create a custom object with the relevant information
                $outputObject = [PSCustomObject]@{
                    Time = $record.time
                    Rule = $flow.rule
                    FlowTuple = $tuple
                    SrcIP = $tupleComponents[1]
                    DestIP = $tupleComponents[2]
                    SrcPort = $tupleComponents[3]
                    DestPort = $tupleComponents[4]
                    Protocol = $tupleComponents[5]
                }

                # Add the custom object to the output array
                $output += $outputObject
            }
        }
    }
}

# Output the results as a table
#$output | Format-Table Time, Rule, SrcIP, DestIP, SrcPort, DestPort, Protocol -AutoSize

$output | Select-Object @{Name="Time"; Expression={([DateTime]$_."Time").ToString("$dateformat")}}, Rule, SrcIP, DestIP, SrcPort, DestPort, Protocol | Format-Table -AutoSize

$exportCSV = Read-Host "Soll eine CSV-Datei exportiert werden? (J/N)"
if ($exportCSV -eq "J") {
    # Export the output as a CSV file with the current date and time in the filename
    $csvFilename = "output_" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".csv"
    $csvFilePath = Join-Path $ExportFolderCSV $csvFilename
    $output | Export-Csv -Path $ExportFolderCSV -NoTypeInformation
    Write-Host "CSV file saved to" $ExportFolderCSV
}

Leon Gawinski

System Engineer Softwarebereich Microsoft

Empfohlene Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Empfehlungen
Schließen
Schaltfläche "Zurück zum Anfang"