Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

pipeline netstat with tasklist

Posted on 2014-01-30
4
Medium Priority
?
928 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 41

Accepted Solution

by:
footech earned 1000 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 71

Assisted Solution

by:Qlemo
Qlemo earned 1000 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 41

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

730 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