Assistance at your fingertips...

Log Specific IPV4 Traffic When Found

'D:\PowerShell\Log-SpecificIPV4Traffic.ps1'
'Run from the PDC'
$ipAddress = Read-host -prompt "What ipv4address? Like 10.8.157.124"
#Cleanup logs
rm -force "D:\powershell\Reports\$ipAddress-logfile.txt"
#Test with known good
<#
Get-NetTCPConnection -state established *|select -first 50
#>
$logFilePath = "D:\powershell\Reports\$ipAddress-logfile.txt"

while ($true) {
    $connection = Get-NetTCPConnection -RemoteAddress $ipAddress
    
    if ($connection) {
        $currentTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        $connection | Out-File -Append -FilePath $logFilePath
        $process = Get-Process -Id $connection.OwningProcess
        Write-Output "[$currentTime] Connection found for IP: $ipAddress" | Out-File -Append -FilePath $logFilePath
        Write-Output "[$currentTime] Process ID: $($connection.OwningProcess)" | Out-File -Append -FilePath $logFilePath
        Write-Output "[$currentTime] Process Name: $($process.Name)" | Out-File -Append -FilePath $logFilePath
        $connection | Format-Table -Property LocalAddress, LocalPort, RemoteAddress, RemotePort, State, AppliedSetting, OwningProcess | Out-File -Append -FilePath $logFilePath
        Write-Host $connection
    } else {
        #$currentTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        Write-Host "[$currentTime] No connection found for IP: $ipAddress. Retrying in 10 seconds..."
        #Write-Output "[$currentTime] No connection found for IP: $ipAddress. Retrying in 10 seconds..." | Out-File -Append -FilePath $logFilePath
    }
    
    Start-Sleep -Seconds 10
}

Posted

in

, ,

by