Connection History with PowerShell and NetStat

Welcome!

This is a little trick some might find useful. I was working on decommissioning some servers and I needed a way to find out what was connecting to these machines. I decided to create a script to log connections. I have done this in the past in various ways which usually involved logging a bunch of data and then querying against it to find the unique connections.

This time it finally occurred to me, just filter the data as it is being collected. So I set out to write a PowerShell script that would keep a running list of client TCP connections to a given machine. This information would be stored in a text file.

The first step was to collect the information and put it into a PowerShell object.

Then the next step was to read the file with the previous information and add it to the PowerShell object.

We can now remove the duplicates from the combined information and save the updated file.

We can run this script in a scheduled task at whatever interval is required. Now we have a log of unique inbound TCP connections.

Best Regards,

Dave

Leave a Reply

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

3 comments

  1. Shay Levy says:

    Try the .NET way, it workd much faster than netstat and there is no need to parse text, it doesn’t do name/port resolution though:

    [System.Net.NetworkInformation.IpGlobalProperties]::GetIPGlobalProperties().GetActiveTcpConnections()

  2. Dave Muegge says:

    Shay,

    Thanks for the tip, I tend to forget about the framework on such common tasks.

  3. Goldstien says:

    Great script – saved me a load of time coding. One small change – I had to explicitly declare all the arrays as I was getting a cannot index into a null array error

    # Create array to hold netstat data
    $allnetstatdata = @()
    $dchost = @()
    $matches = @()
    $foreignhost =@()

    I now need to add to your script a lookup of the client machines and their owners in both active directory and the CMDB database.. Might take a little while but I think it should be quicker than doing it manually for 800 servers 😀