Thursday, February 12, 2009

This function pushes off the stack every new Established TCP connection as so:

PS >List-EstablishedTCP
209.62.20.43 ev1s-209-62-20-43.theplanet.com : 80
72.30.190.105 rc10.ysm.vip.ac2.yahoo.com : 80
165.160.9.37 165.160.9.37 : 80
66.235.133.3 dc2-3.112.2o7.net : 80
75.101.151.37 ec2-75-101-151-37.compute-1.amazonaws.com : 80
8.12.226.77 8.12.226.77 : 80
96.17.232.242 a96-17-232-242.deploy.akamaitechnologies.com : 80

It also send a message to the (classic) Event Log named "EstablishedTCPConnections" as shown here.  One PoSh blog was very helpful with this: http://winpowershell.blogspot.com/2006/07/writing-windows-events-using.html

function Global:EstablishedTCP 
{ ## start function

    $a = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
    $b = $a.GetActiveTcpConnections() | where{$_.State -eq "Established" }
        
    if ($b -ne $null -and $last_b -ne $null) 
    {
    $c = compare-object $b $last_b;
    }
    
    if ($c.SideIndicator -eq "<=" )
        {        
        $LocalAddress = $c.InputObject.LocalEndPoint.Address
        $RemoteAddress = $c.InputObject.RemoteEndPoint.Address           
        $LocalPort = $c.InputObject.LocalEndPoint.Port
        $RemotePort = $c.InputObject.RemoteEndPoint.Port
        
        $name = [System.Net.DNS]::Resolve("$RemoteAddress")
        $name_canon = $name.hostname
        
        write "$RemoteAddress $name_canon : $RemotePort"
        
        $EventLog = new-object System.Diagnostics.EventLog("EstablishedTCPConnections") 
        $EventLog.Source = "$name_canon" 
        $infoevent = [System.Diagnostics.EventLogEntryType]::Information 
        $EventLog.WriteEntry("$LocalAddress established connection to $RemoteAddress ($name_canon) from Local Port: $LocalPort to Remote Port: $RemotePort",$infoevent,$RemotePort,01) 
        }

start-sleep -m 100
$global:last_b = $b
  
} ## end function Established

function global:List-EstablishedTCP {do {EstablishedTCP} while (1)}

No comments: