Wednesday, July 1, 2015

Quick Script - Find which servers are connecting to your 2003 boxes

With Windows server 2008, we got the lovely Resmon.exe tool which lets you easily see TCP/IP connections, complete with reverse name lookup. This has proven invaluable in troubleshooting issues. But what do you do about your 2003 servers that you are still supportting? Here's a quick script which uses the legacy tool netstat.exe to create a properly formed Powershell table (object array). Remember, UDP is stateless, so it doesn't ever have data for the connection state column.

PS C:\> ((netstat -a | select -skip 4) -replace '^\s+','') -replace '\s+',',' |
>>>     ConvertFrom-Csv -Header ("Protocol","Local Address","Foreign Address","State") |
>>>     sort state -Descending| FT -AutoSize

Protocol Local Address         Foreign Address         State
-------- -------------         ---------------         -----
TCP      127.0.0.1:61840       server10:8080           SYN_SENT
TCP      127.0.0.1:31014       MyPCname:0              LISTENING
TCP      127.0.0.1:63202       server20:443            ESTABLISHED
TCP      192.168.0.2:61819     server30:1433           CLOSE_WAIT
UDP      127.0.0.1:64204       *:*



If you wish to get the processID, just change "netstat -a" to "netstat -ao" and add ,"PID" to the Header line like this. Note: the columns now don't parse correctly for UDP because of how things are being split up. It's possible to fix, but most of the time spent troubleshooting will probably be spent on TCP connections.
PS C:\> ((netstat -ao | select -skip 4) -replace '^\s+','') -replace '\s+',',' |
>>>     ConvertFrom-Csv -Header ("Protocol","Local Address","Foreign Address","State","PID") |
>>>     sort state -Descending| FT -AutoSize

Protocol Local Address         Foreign Address        State        PID
-------- -------------         ---------------        -----        ---
TCP      127.0.0.1:61840       server10:8080          SYN_SENT     1235
TCP      127.0.0.1:31014       MyPCname:0             LISTENING    8765
TCP      127.0.0.1:63202       server20:443           ESTABLISHED  2345
TCP      192.168.0.2:61819     server30:1433          CLOSE_WAIT   3454
UDP      127.0.0.1:64204       *:*                    234

No comments: