Get foreign address name using NETSTAT for established active TCP connections

后端 未结 3 677
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 05:21

I\'m using NETSTAT command in PowerShell. I need to grab the list of foreign addresses which starts with XYZ name and are ESTABLISHED as state using TCP connections.

<
相关标签:
3条回答
  • 2020-12-20 05:58

    +1 for @E.V.I.L. answer but it chokes the (slow) stream from NetStat due to the assignments ($netstats and $final). To keep the pipeline streaming, it is better to avoid assignments, like:

    netstat -p TCP -f | Select -Skip 4 | ForEach {
        $Properties = $_.Trim() -split '[\s]+'
        [PSCustomObject]@{
            'Proto'= $Properties[0]
            'Local Address'= $Properties[1]
            'Foreign Address'= $Properties[2]
            'State'= $Properties[3]
        }
    }
    

    By adding e.g. | Select -Expand 'Foreign Address', you just get the Foreign Address.

    0 讨论(0)
  • 2020-12-20 06:01

    Running netstat /? yields, among other things:

    -f Displays Fully Qualified Domain Names (FQDN) for foreign addresses.

    Parse, using New-PSObjectFromMatches:

    netstat -f |
     new-psobjectfrommatches -pattern "(TCP|UDP)\s+(\S+)\s+(\S+):(\S+)\s+(\S+)" -property $nul,TCP/UDP,LocalAddress,ForeignAddress,Protocol,State |
     where {(
             ($_.TCP/UDP -eq 'TCP') -and
             ($_.State -eq 'ESTABLISHED') -and
             ($_.ForeignAddress -like 'XYZ*')
            )} | select -ExpandProperty ForeignAddress 
    
    0 讨论(0)
  • 2020-12-20 06:06
     $netstats = netstat -p TCP -f
     $data = $netstats[4..($netstats.count)] #The good info starts on index 4
     foreach($line in $data){
         $line = $line -split ' ' | ? {$_ -ne ''}
         $final += @(New-Object -TypeName psobject -Property @{'Proto'=$line[0];'LAddress'=$line[1];'FAddress'=$line[2];'State'=$line[3]})
     }
     $netstat_results = $final
     $netstat_results | ? {$_.state -eq 'ESTABLISHED'}
    

    Now it should be easy getting the data you want after parsing the text that netstat returns.

    0 讨论(0)
提交回复
热议问题