Solved

pipeline netstat with tasklist

Posted on 2014-01-30
4
813 Views
Last Modified: 2014-01-31
I have two commands I want to serialize and output a list of ports mapped to services, using the PID column. Specifically, the "Local Address" column from netstat -ano would pair nicely with the "Image Name" column from the tasklist /svc command.

Would you help me understand how to link these two commands where the output pairs "Local Address" with "Image Name", keyed off the common PID column from each command?

Thanks!
JohnD
0
Comment
Question by:johndarby
  • 2
4 Comments
 
LVL 39

Accepted Solution

by:
footech earned 250 total points
ID: 39823408
Thought this was kind of interesting.  I modified the code found at http://poshcode.org/2701 to add a -svc switch parameter to the function which will display some info about associated services.

function Get-NetworkStatistics
{
        [OutputType('System.Management.Automation.PSObject')]
        [CmdletBinding(DefaultParameterSetName='name')]
           
        param(
                [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='port')]
                [System.Int32]$Port,
                   
                [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='name')]
                [System.String]$ProcessName='*',
                   
                [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='address')]
                [System.String]$Address='*',           
                   
                [Parameter()]
                [ValidateSet('*','tcp','udp')]
                [System.String]$Protocol='*',
     
                [Parameter()]
                [ValidateSet('*','Closed','CloseWait','Closing','DeleteTcb','Established','FinWait1','FinWait2','LastAck','Listen','SynReceived','SynSent','TimeWait','Unknown')]
                [System.String]$State='*',

                [Parameter()]
                [switch]$Svc
                   
        )
       
        begin
        {
                $properties = 'Protocol','LocalAddress','LocalPort'
                $properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'
                if ($Svc)
                {
                    $properties += 'Services'
                    $svclist = Get-WmiObject Win32_Service -filter "ProcessID != 0" | Select Name, ProcessID
                }
        }
           
        process
        {
            netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {
     
                $item = $_.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
     
                if($item[1] -notmatch '^\[::')
                {          
                    if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
                    {
                        $localAddress = $la.IPAddressToString
                        $localPort = $item[1].split('\]:')[-1]
                    }
                    else
                    {
                        $localAddress = $item[1].split(':')[0]
                        $localPort = $item[1].split(':')[-1]
                    }
     
                    if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
                    {
                        $remoteAddress = $ra.IPAddressToString
                        $remotePort = $item[2].split('\]:')[-1]
                    }
                    else
                    {
                        $remoteAddress = $item[2].split(':')[0]
                        $remotePort = $item[2].split(':')[-1]
                    }
                                   
                                $procId = $item[-1]
                                $procName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
                                $proto = $item[0]
                                $status = if($item[0] -eq 'tcp') {$item[3]} else {$null}                               
                                   
                                
                                if ($Svc)
                                {
                                    $pso = New-Object -TypeName PSObject -Property @{
                                            PID = $procId
                                            ProcessName = $procName
                                            Protocol = $proto
                                            LocalAddress = $localAddress
                                            LocalPort = $localPort
                                            RemoteAddress = $remoteAddress
                                            RemotePort = $remotePort
                                            State = $status
                                            Services = ($svclist | Where { $_.ProcessID -eq $procId } | Select -ExpandProperty Name) -join ", "
                                    } | Select-Object -Property $properties
                                }
                                else
                                {
                                    $pso = New-Object -TypeName PSObject -Property @{
                                            PID = $procId
                                            ProcessName = $procName
                                            Protocol = $proto
                                            LocalAddress = $localAddress
                                            LocalPort = $localPort
                                            RemoteAddress = $remoteAddress
                                            RemotePort = $remotePort
                                            State = $status
                                    } | Select-Object -Property $properties
                                }
     
     
                                if($PSCmdlet.ParameterSetName -eq 'port')
                                {
                                        if($pso.RemotePort -like $Port -or $pso.LocalPort -like $Port)
                                        {
                                            if($pso.Protocol -like $Protocol -and $pso.State -like $State)
                                                {
                                                        $pso
                                                }
                                        }
                                }
     
                                if($PSCmdlet.ParameterSetName -eq 'address')
                                {
                                        if($pso.RemoteAddress -like $Address -or $pso.LocalAddress -like $Address)
                                        {
                                            if($pso.Protocol -like $Protocol -and $pso.State -like $State)
                                                {
                                                        $pso
                                                }
                                        }
                                }
                                   
                                if($PSCmdlet.ParameterSetName -eq 'name')
                                {              
                                        if($pso.ProcessName -like $ProcessName)
                                        {
                                                if($pso.Protocol -like $Protocol -and $pso.State -like $State)
                                                {
                                                        $pso
                                                }
                                        }
                                }
                }
            }
        }
<#
     
.SYNOPSIS
        Displays the current TCP/IP connections.
     
.DESCRIPTION
        Displays active TCP connections and includes the process ID (PID) and Name for each connection.
        If the port is not yet established, the port number is shown as an asterisk (*).       
           
.PARAMETER ProcessName
        Gets connections by the name of the process. The default value is '*'.
           
.PARAMETER Port
        The port number of the local computer or remote computer. The default value is '*'.
     
.PARAMETER Address
        Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
     
.PARAMETER Protocol
        The name of the protocol (TCP or UDP). The default value is '*' (all)
           
.PARAMETER State
        Indicates the state of a TCP connection. The possible states are as follows:
                   
        Closed          - The TCP connection is closed.
        CloseWait       - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
        Closing         - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
        DeleteTcb       - The transmission control buffer (TCB) for the TCP connection is being deleted.
        Established     - The TCP handshake is complete. The connection has been established and data can be sent.
        FinWait1        - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
        FinWait2        - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
        LastAck         - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
        Listen          - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
        SynReceived     - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
        SynSent         - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
        TimeWait        - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
        Unknown         - The TCP connection state is unknown.
           
        Values are based on the TcpState Enumeration:
        http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
     
.EXAMPLE
        Get-NetworkStatistics
     
.EXAMPLE
        Get-NetworkStatistics iexplore
     
.EXAMPLE
        Get-NetworkStatistics -ProcessName md* -Protocol tcp
     
.EXAMPLE
        Get-NetworkStatistics -Address 192* -State LISTENING
     
.EXAMPLE
        Get-NetworkStatistics -State LISTENING -Protocol tcp
     
.EXAMPLE
        Get-NetworkStatistics -Svc

.OUTPUTS
        System.Management.Automation.PSObject
     
.NOTES
        Based off work by: Shay Levy
        Blog  : http://PowerShay.com
#>     
}
     
help Get-NetworkStatistics

Open in new window

It outputs PsObjects, so you can customize which properties you want to display, etc.  Here's an example.
Get-NetworkStatistics -svc | select protocol,localport,processname,pid,services | sort localport -Unique | ft -auto -Wrap

Open in new window

0
 
LVL 68

Assisted Solution

by:Qlemo
Qlemo earned 250 total points
ID: 39823425
Instead of using netstat -ano, it might be easier to use www.sysinternals.com' TcpVCon -ac, which output as CSV is much easier to process.

Do you want to get the complete list, or ask for a specific service or process?
0
 
LVL 39

Expert Comment

by:footech
ID: 39823578
@Qlemo -  :)  I had thought of that.  If I was starting out from scratch I would probably use that output instead, but since someone had already done the work of parsing netstat I just added on to that.
0
 
LVL 1

Author Closing Comment

by:johndarby
ID: 39824179
Thanks guys; I think I will write a custom app in C# to do the job; I want to hand off something portable to my guys in the lab; thank you!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article shows how a content item can be identified directly or through translation of a navigation type. It then shows how this information can be used to create a menu for further navigation.
How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now