Network Traffic Analyzer Tool

<#
.SYNOPSIS
Network Traffic Analyzer Tool

.DESCRIPTION
This script analyzes network traffic, connections, and performance across servers in your network.

.NOTES
File Name      : NetworkTrafficAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, appropriate admin permissions, NetAdapter and NetTCPIP modules
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\NetworkTrafficAnalyzer.ps1
#>

# Import required modules
Import-Module NetAdapter
Import-Module NetTCPIP

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\Network_Traffic_Analysis_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Network Traffic Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze Network Adapter Performance"
    Write-Host "2. Check Active TCP Connections"
    Write-Host "3. Analyze Network Bandwidth Usage"
    Write-Host "4. Check Network Latency"
    Write-Host "5. Analyze IP Configuration"
    Write-Host "6. Check Network Protocol Statistics"
    Write-Host "7. Analyze Firewall Rules"
    Write-Host "8. Generate Comprehensive HTML Report"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Gets a list of servers to analyze.

.OUTPUTS
Array of server names.
#>
function Get-TargetServers {
    $option = Read-Host "Analyze (L)ocal machine, (S)pecific servers, or (F)ile input? (L/S/F)"
    switch ($option.ToUpper()) {
        "L" {
            return @($env:COMPUTERNAME)
        }
        "S" {
            $servers = @()
            do {
                $server = Read-Host "Enter server name (or press Enter to finish)"
                if ($server -ne "") { $servers += $server }
            } while ($server -ne "")
            return $servers
        }
        "F" {
            $filePath = Read-Host "Enter the path to the file containing server names"
            return (Get-Content $filePath)
        }
        default {
            Write-Host "Invalid option. Defaulting to local machine." -ForegroundColor Yellow
            return @($env:COMPUTERNAME)
        }
    }
}

<#
.SYNOPSIS
Analyzes network adapter performance.

.PARAMETER Servers
Array of server names to analyze.

.OUTPUTS
Array of PSObjects containing network adapter performance details.
#>
function Analyze-NetworkAdapterPerformance {
    param([string[]]$Servers)

    Write-Host "`nAnalyzing Network Adapter Performance..." -ForegroundColor Yellow
    $adapterResults = @()
    foreach ($server in $Servers) {
        try {
            $adapters = Get-NetAdapter -CimSession $server -ErrorAction Stop
            foreach ($adapter in $adapters) {
                $stats = $adapter | Get-NetAdapterStatistics
                $adapterResults += [PSCustomObject]@{
                    Server = $server
                    AdapterName = $adapter.Name
                    LinkSpeed = $adapter.LinkSpeed
                    BytesReceived = $stats.ReceivedBytes
                    BytesSent = $stats.SentBytes
                    Status = $adapter.Status
                }
            }
        }
        catch {
            Write-Host "Error analyzing network adapters on $server : $_" -ForegroundColor Red
        }
    }
    $adapterResults | Format-Table -AutoSize
    return $adapterResults
}

<#
.SYNOPSIS
Checks active TCP connections.

.PARAMETER Servers
Array of server names to analyze.

.OUTPUTS
Array of PSObjects containing active TCP connection details.
#>
function Check-ActiveTCPConnections {
    param([string[]]$Servers)

    Write-Host "`nChecking Active TCP Connections..." -ForegroundColor Yellow
    $connectionResults = @()
    foreach ($server in $Servers) {
        try {
            $connections = Get-NetTCPConnection -CimSession $server -ErrorAction Stop | 
                           Where-Object {$_.State -eq 'Established'}
            foreach ($conn in $connections) {
                $connectionResults += [PSCustomObject]@{
                    Server = $server
                    LocalAddress = $conn.LocalAddress
                    LocalPort = $conn.LocalPort
                    RemoteAddress = $conn.RemoteAddress
                    RemotePort = $conn.RemotePort
                    State = $conn.State
                }
            }
        }
        catch {
            Write-Host "Error checking TCP connections on $server : $_" -ForegroundColor Red
        }
    }
    $connectionResults | Format-Table -AutoSize
    return $connectionResults
}

<#
.SYNOPSIS
Analyzes network bandwidth usage.

.PARAMETER Servers
Array of server names to analyze.

.OUTPUTS
Array of PSObjects containing network bandwidth usage details.
#>
function Analyze-NetworkBandwidthUsage {
    param([string[]]$Servers)

    Write-Host "`nAnalyzing Network Bandwidth Usage..." -ForegroundColor Yellow
    $bandwidthResults = @()
    foreach ($server in $Servers) {
        try {
            $adapters = Get-NetAdapter -CimSession $server -ErrorAction Stop
            foreach ($adapter in $adapters) {
                $initialStats = $adapter | Get-NetAdapterStatistics
                Start-Sleep -Seconds 5
                $finalStats = $adapter | Get-NetAdapterStatistics
                $receivedBps = ($finalStats.ReceivedBytes - $initialStats.ReceivedBytes) / 5
                $sentBps = ($finalStats.SentBytes - $initialStats.SentBytes) / 5
                
                $bandwidthResults += [PSCustomObject]@{
                    Server = $server
                    AdapterName = $adapter.Name
                    ReceiveBandwidth = "$([math]::Round($receivedBps / 1MB, 2)) MBps"
                    SendBandwidth = "$([math]::Round($sentBps / 1MB, 2)) MBps"
                }
            }
        }
        catch {
            Write-Host "Error analyzing bandwidth usage on $server : $_" -ForegroundColor Red
        }
    }
    $bandwidthResults | Format-Table -AutoSize
    return $bandwidthResults
}

<#
.SYNOPSIS
Checks network latency.

.PARAMETER Servers
Array of server names to analyze.

.OUTPUTS
Array of PSObjects containing network latency details.
#>
function Check-NetworkLatency {
    param([string[]]$Servers)

    Write-Host "`nChecking Network Latency..." -ForegroundColor Yellow
    $latencyResults = @()
    foreach ($server in $Servers) {
        try {
            $ping = Test-Connection -ComputerName $server -Count 4 -ErrorAction Stop
            $latencyResults += [PSCustomObject]@{
                Server = $server
                MinLatency = ($ping | Measure-Object -Property ResponseTime -Minimum).Minimum
                MaxLatency = ($ping | Measure-Object -Property ResponseTime -Maximum).Maximum
                AverageLatency = ($ping | Measure-Object -Property ResponseTime -Average).Average
            }
        }
        catch {
            Write-Host "Error checking network latency for $server : $_" -ForegroundColor Red
        }
    }
    $latencyResults | Format-Table -AutoSize
    return $latencyResults
}

<#
.SYNOPSIS
Analyzes IP configuration.

.PARAMETER Servers
Array of server names to analyze.

.OUTPUTS
Array of PSObjects containing IP configuration details.
#>
function Analyze-IPConfiguration {
    param([string[]]$Servers)

    Write-Host "`nAnalyzing IP Configuration..." -ForegroundColor Yellow
    $ipConfigResults = @()
    foreach ($server in $Servers) {
        try {
            $ipConfig = Get-NetIPConfiguration -CimSession $server -ErrorAction Stop
            foreach ($config in $ipConfig) {
                $ipConfigResults += [PSCustomObject]@{
                    Server = $server
                    InterfaceAlias = $config.InterfaceAlias
                    IPv4Address = $config.IPv4Address.IPAddress
                    IPv6Address = $config.IPv6Address.IPAddress
                    DefaultGateway = $config.IPv4DefaultGateway.NextHop
                    DNSServer = ($config.DNSServer | Where-Object {$_.AddressFamily -eq 2}).ServerAddresses -join ', '
                }
            }
        }
        catch {
            Write-Host "Error analyzing IP configuration on $server : $_" -ForegroundColor Red
        }
    }
    $ipConfigResults | Format-Table -AutoSize
    return $ipConfigResults
}

<#
.SYNOPSIS
Checks network protocol statistics.

.PARAMETER Servers
Array of server names to analyze.

.OUTPUTS
Array of PSObjects containing network protocol statistics.
#>
function Check-NetworkProtocolStatistics {
    param([string[]]$Servers)

    Write-Host "`nChecking Network Protocol Statistics..." -ForegroundColor Yellow
    $protocolStats = @()
    foreach ($server in $Servers) {
        try {
            $tcpStats = Get-NetTCPStatistics -CimSession $server -ErrorAction Stop
            $udpStats = Get-NetUDPStatistics -CimSession $server -ErrorAction Stop
            $protocolStats += [PSCustomObject]@{
                Server = $server
                TCPSegmentsSent = $tcpStats.SegmentsSent
                TCPSegmentsReceived = $tcpStats.SegmentsReceived
                TCPConnectionsReset = $tcpStats.ConnectionsReset
                UDPDatagramsReceived = $udpStats.DatagramsReceived
                UDPDatagramsSent = $udpStats.DatagramsSent
            }
        }
        catch {
            Write-Host "Error checking network protocol statistics on $server : $_" -ForegroundColor Red
        }
    }
    $protocolStats | Format-Table -AutoSize
    return $protocolStats
}

<#
.SYNOPSIS
Analyzes firewall rules.

.PARAMETER Servers
Array of server names to analyze.

.OUTPUTS
Array of PSObjects containing firewall rule details.
#>
function Analyze-FirewallRules {
    param([string[]]$Servers)

    Write-Host "`nAnalyzing Firewall Rules..." -ForegroundColor Yellow
    $firewallResults = @()
    foreach ($server in $Servers) {
        try {
            $rules = Get-NetFirewallRule -CimSession $server -ErrorAction Stop
            $firewallResults += [PSCustomObject]@{
                Server = $server
                TotalRules = $rules.Count
                EnabledRules = ($rules | Where-Object {$_.Enabled -eq $true}).Count
                InboundRules = ($rules | Where-Object {$_.Direction -eq 'Inbound'}).Count
                OutboundRules = ($rules | Where-Object {$_.Direction -eq 'Outbound'}).Count
            }
        }
        catch {
            Write-Host "Error analyzing firewall rules on $server : $_" -ForegroundColor Red
        }
    }
    $firewallResults | Format-Table -AutoSize
    return $firewallResults
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
function Generate-HTMLReport {
    param([hashtable]$AllResults)

    Write-Host "`nGenerating Comprehensive HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Network Traffic Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>Network Traffic Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>Network Adapter Performance</h2>
    $($AllResults.AdapterPerformance | ConvertTo-Html -Fragment)

    <h2>Active TCP Connections</h2>
    $($AllResults.TCPConnections | ConvertTo-Html -Fragment)

    <h2>Network Bandwidth Usage</h2>
    $($AllResults.BandwidthUsage | ConvertTo-Html -Fragment)

    <h2>Network Latency</h2>
    $($AllResults.NetworkLatency | ConvertTo-Html -Fragment)

    <h2>IP Configuration</h2>
    $($AllResults.IPConfiguration | ConvertTo-Html -Fragment)

    <h2>Network Protocol Statistics</h2>
    $($AllResults.ProtocolStats | ConvertTo-Html -Fragment)

    <h2>Firewall Rules</h2>
    $($AllResults.FirewallRules | ConvertTo-Html -Fragment)
</body>
</html>
"@

    $reportContent | Out-File -FilePath $global:reportPath
    Write-Host "Report generated and saved to: $global:reportPath" -ForegroundColor Green
}

# Main program loop
$targetServers = Get-TargetServers
$allResults = @{}

do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-9)"

    switch ($choice) {
        "1" { $allResults.AdapterPerformance = Analyze-NetworkAdapterPerformance -Servers $targetServers }
        "2" { $allResults.TCPConnections = Check-ActiveTCPConnections -Servers $targetServers }
        "3" { $allResults.BandwidthUsage = Analyze-NetworkBandwidthUsage -Servers $targetServers }
        "4" { $allResults.NetworkLatency = Check-NetworkLatency -Servers $targetServers }
        "5" { $allResults.IPConfiguration = Analyze-IPConfiguration -Servers $targetServers }
        "6" { $allResults.ProtocolStats = Check-NetworkProtocolStatistics -Servers $targetServers }
        "7" { $allResults.FirewallRules = Analyze-FirewallRules -Servers $targetServers }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "9") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "9")

This Network Traffic Analyzer Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various aspects of network traffic and performance:
    • Network Adapter Performance analysis
    • Active TCP Connections check
    • Network Bandwidth Usage analysis
    • Network Latency check
    • IP Configuration analysis
    • Network Protocol Statistics check
    • Firewall Rules analysis
  3. Flexible server selection (local machine, specific servers, or from a file).
  4. Comprehensive error handling for each analysis function.
  5. A function to generate an HTML report of all collected data.

Key features:

  • Detailed analysis of network adapter performance across multiple servers
  • Checking of active TCP connections
  • Real-time bandwidth usage measurement
  • Network latency analysis
  • Comprehensive IP configuration review
  • Analysis of TCP and UDP protocol statistics
  • Overview of firewall rules
  • HTML report generation for easy sharing and viewing of results

This tool is particularly useful for:

  • Network administrators troubleshooting performance issues
  • System administrators managing server networks
  • IT professionals performing network health checks
  • Security teams reviewing network configurations

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions to query the target servers
  3. Have the required PowerShell modules available (NetAdapter and NetTCPIP)

This script provides a comprehensive overview of network traffic and performance across multiple servers in your network. It can significantly streamline the process of diagnosing network issues, optimizing performance, and maintaining network security.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *