Solved

pipeline netstat with tasklist

Posted on 2014-01-30
4
857 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 40

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 69

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 40

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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

856 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