Thursday, February 5, 2009

Netstat.ps1

Update 03/30/2012:
More work I did on this problem:




[back to original post...]


I spent some time seeing if Powershell could deliver some 'lsof' functionality easily with little luck. Few windows utilities do this now. Some exceptions are 'netstat -bno' (XPSP3) or tcpview.exe.  Powershell (or at least me with Powershell) can't do much with the TCPState interface despite the presence of static members:

PS > [System.Net.NetworkInformation.TcpState].GetMembers() | % {$_.Name}
...
Unknown
Closed
Listen
SynSent
SynReceived
Established
FinWait1
FinWait2
CloseWait
Closing
LastAck
TimeWait
DeleteTcb

This interface: [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
was more useful:

[netstat.ps1]
$a = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
$b = $a.GetActiveTcpListeners() | Select Address,Port | Sort Port
$c = $a.GetActiveUDPListeners() | Select Address,Port | Sort Port
$d = $a.GetActiveTcpConnections() | Select LocalEndPoint,RemoteEndPoint,State | Sort State,RemoteEndPoint
write "TCP Listeners" $b | ft -auto
write "UDP Listeners" $c | ft -auto
write "TCP Active Connections" $d | ft -auto


PS >.\netstat.ps1
TCP Listeners

Address     Port
-------     ----
0.0.0.0      135
192.168.0.5  139
192.168.0.8  139
0.0.0.0      445
127.0.0.1   1027
0.0.0.0     3389


UDP Listeners

Address     Port
-------     ----
127.0.0.1    123
192.168.0.8  123
192.168.0.5  123
192.168.0.5  137
192.168.0.8  137
192.168.0.5  138
192.168.0.8  138
0.0.0.0      445
0.0.0.0      500
192.168.0.5 1900
127.0.0.1   1900
192.168.0.8 1900
127.0.0.1   2139
127.0.0.1   2683
127.0.0.1   2704
0.0.0.0     4500


TCP Active Connections

LocalEndPoint    RemoteEndPoint          State
-------------    --------------          -----
127.0.0.1:1266   127.0.0.1:1265    Established
127.0.0.1:1265   127.0.0.1:1266    Established
127.0.0.1:1268   127.0.0.1:1267    Established
127.0.0.1:1267   127.0.0.1:1268    Established
192.168.0.8:2877 65.55.11.254:80   Established
192.168.0.8:2876 72.14.207.191:80  Established
192.168.0.8:1062 209.85.173.102:80   CloseWait


No comments: