PowerShell Script to Log Network Connections

General Description

The Log-Connections.ps1 file is a PowerShell Script that Logs active TCP connections and includes the process ID (PID) and process name for each connection on a Microsoft Windows computer.  The log file name is a parameter that is passed to the script at run time.  A log entry is created every time that the list of processes with open connections or listening ports changes.  If the ports or remote addresses are not yet established, they are shown as an asterisk (*).

The Log-Connections script is based on the netstat command, “netstat –nao,” which can be run at the Windows command prompt to display a snapshot of all connections and listening ports.  The –o switch tells netstat to display the owning process ID that is associated with each process.  A limitation of the netstat command is that it cannot report the associated process name, just the PID.   To achieve this, the Log-Connections PowerShell script calls the Get-NetworkStatistics function.   This function was written by Shay Levy and is available at http://poshcode.org/2701 .

The Log-Connections script calls the Get-NetworkStatistics function repeatedly in an infinite loop, comparing the current snapshot with the previous.  If there is a change, the current snapshot is time stamped, logged to the file, and optionally passed through to the PowerShell pipeline.

Passing the connections snapshot object through to the PowerShell pipeline allows the data to be manipulated or displayed in real-time by other PowerShell cmdlets.  This will be illustrated in the examples that follow.

Quick Intro to PowerShell

Windows PowerShell is a command-line shell and a scripting language that is built upon the .NET Framework. PowerShell has been around since 2006, but is included in the base OS with Windows 7 and Windows Server 2008 R2.

Windows Search Box PowerShell can be invoked by typing “powershell” in the search box above the Windows Start Button, or by typing “powershell” at the Windows command prompt.

A great website to learn more about PowerShell is at http://www.powershellpro.com/powershell-tutorial-introduction/.

 

PowerShell Security Features

PowerShell has an script execution policy that by default will prevent scripts from being executed unintentionally.  To learn more about execution policies, type the following command in PowerShell:

Get-Help about_Execution_Policies

To be able to run the following examples, it is suggested that you change the execution policy to “RemoteSigned” so that local scripts can run unsigned and remote scripts can only run if signed by a trusted entity.  To do this run the following PowerShell command:

Set-ExecutionPolicy RemoteSigned –scope CurrentUser

To revert back to the default, just type:

Set-ExecutionPolicy Restricted

Another feature of PowerShell is that scripts cannot be executed in the current directory by typing just the script name.  Instead they must be prefaced with a dot and a backslash, ( “.\”).  This is illustrated in the examples below.

EXAMPLE 1

powershell .\Log-Connections.ps1 c:\workspace\mylog.csv

Example 1 Screenshot

Example 1 shows the Log-Connections.ps1 script being invoked from the Windows command prompt. The ps1 script and the complete path to the log file are passed in as arguments the command “powershell.”  Also note the use the file extension of “CSV.”  This is convenient because on many systems when a CSV file is double clicked it will launch Microsoft Excel.  Any other extension, including “TXT” is also acceptable.

EXAMPLE 2

powershell c:\Temp\Log-Connections.ps1 mylog.csv svchost

Example 2 Screenshot

Example 2 is very similar to the first one except a process name has been passed in as an argument and just the file name (without the path) has been provided, so the log file will be saved in the current directory, c:\workspace.  The full path to the script is provided because it is in c:\temp.

Note: if the log file exists already, the new observations will be appended to the bottom

EXAMPLE 3

powershell .\Log-Connections.ps1 mylog.csv svchost -PassThru

Example-3

Using the “-PassThru” switch will cause the script display the results to the screen in a raw format in addition to logging them in the log file.

EXAMPLE 4

.\Log-Connections.ps1 -ProcName svchost -Filepath mylog.csv

Example 4 Screenshot

In Example 4 the user typed “powershell” at the command prompt to invoke PowerShell. Then the name of the script and its arguments were typed at the PowerShell prompt.

This example also demonstrated the use of the named parameters convention.  Passing in the parameter value (e.g. “mylog.csv”)  after the parameter name (“-Filepath”) allows the parameters to be passed in out of order.

EXAMPLE 5

.\Log-Connections.ps1

Example 5 Screenshot

Example 6 shows that PowerShell will gracefully request any missing parameters that are mandatory. In this case it is the FilePath value.

EXAMPLE 6

.\Log-Connections.ps1 mylog.csv svchost -PassThru | Format-Table

Example-6

Example 6 illustrates piping the output of the Log-Connections script to the Format-Table cmdlet.  The Format-Table cmdlet produces a nice table of the results that will grow in real time.

EXAMPLE 7

.\Log-Connections.ps1 mylog.csv iexplore -PassThru | Out-GridView

Example 7 Screen

Using the Out-Gridview cmdlet, as shown in Example 7, will produce a grid of the results.  The grid grows in real time and can be filtered and sorted.  The columns can also be re-arranged.

Example of a PowerShell Grid

The grid can also be filtered using the “Add Criteria” button as shown below:

Example-Filtered-Grid

 

Tagged , . Bookmark the permalink.
  • The postings and views on this site are my own and do not necessarily reflect the positions, strategies, or opinions of any current or previous employer.