Powershell按端口搜索TCP连接

时间:2019-01-26 23:33:13

标签: powershell tcp

我无法在PowerShell中找到任何可以完成netstat之类的已发布代码,然后按端口搜索已建立的TCP连接。

我编写了以下功能,该功能有效,希望获得一些反馈。有没有更简单的方法?我的公司仍在Windows 7上,因此我无法使用Get-NetTcpConnection

<# Get-ESTConnectionByPort
Usage: Pass the port number to the function and it will return a boolian
value of true or false it will also echo an "Connected" or "Not Connected"
output to the console.
Get-ESTConnectionbyPort -Port "443"
#>
function Get-ESTConnectionByPort {
    Param($Port)

    $NetworkProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()

    $TcpConnections = $NetworkProperties.GetActiveTcpConnections()

    $TCPOut = $TcpConnections | Select-Object State, RemoteEndPoint

    $TCPTable = @($TCPOut.where({
        $_.RemoteEndPoint -match '.:' + $Port + '\z' -and
        $_.State -eq "Established"
    }))

    $Value = (-not $TCPTable)

    if (-not $Value) {
        Write-Host "Connected"
        $script:TCPConnected = $true
    } else {
        Write-Host "Not Connected"
        $script:TCPConnected = $false
    }

    $script:TCPConnected
}

2 个答案:

答案 0 :(得分:0)

这以略有不同的方式完成工作。它使用.Where().ForEach()数组方法稍微加快了速度。如果运行PS2或PS3,则需要用其管道版本[Where-ObjectForEach-Object]替换它们。

它允许选择多个端口号和多个状态,然后生成一个[PSCusomtObject],按端口排序,最后输出对象。没有其他输出。

function Get-TcpConnectionInfo
    {
    <#
    Comment Based Help goes here
    #>

    [CmdletBinding ()]
    Param (
        [Parameter (
            Position = 0
            )]
            [int[]]
            $Port = 443,

        [Parameter (
            Position = 1
            )]
            [ValidateSet (
                'Established',
                'CloseWait',
                'TimeWait'
                )]
            [string[]]
            $State = 'Established'
        )

    begin {}

    process
        {
        $State = @($State).ForEach({$_.ToLower()})

        @([System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().
            GetActiveTcpConnections()).
            Where({
                # include only foreign RemoteEndPoint items
                $_.LocalEndPoint.Address -ne $_.RemoteEndPoint.Address -and
                $_.State.ToString().ToLower() -in $State -and
                $_.RemoteEndPoint.Port -in $Port
                }).
            ForEach({
                [PSCustomObject]@{
                    State = $_.State
                    RemoteEndPoint = $_.RemoteEndPoint
                    }
                }) |
            Sort-Object {$_.RemoteEndPoint.Port}
        }

    end {}

    } # end >> function Get-TcpConnectionInfo

通过以下呼叫...

Get-TcpConnectionInfo -Port 443, 993 -State closewait, established

...它返回这个...

      State RemoteEndPoint    
      ----- --------------    
  CloseWait 13.33.115.238:443 
Established 151.101.65.69:443 
Established 198.252.206.25:443
Established 23.194.113.80:443 
Established 40.97.120.242:993 
Established 173.194.70.108:993
Established 173.194.70.108:993
Established 40.97.120.242:993

答案 1 :(得分:0)

无需重新发明轮子。

有一个专门用于此操作的cmdlet,除非您使用的操作系统或更低版本的PowerShell没有此命令。

# get function / cmdlet details
(Get-Command -Name Test-NetConnection).Parameters
Get-help -Name Test-NetConnection -Examples

<#
    Example 3: Test TCP connectivity and display detailed results

    PS C:\> Test-NetConnection -Port 80 -InformationLevel "Detailed"
    ComputerName            : internetbeacon.msedge.net
    RemoteAddress           : 2a01:111:2003::52
    RemotePort              : 80
    NameResolutionResults   : 2a01:111:2003::52
                            13.107.4.52
    MatchingIPsecRules      : Ipsec/Domain-TrafficFromInternet-v6
    NetworkIsolationContext : Internet
    IsAdmin                 : False
    InterfaceAlias          : Ethernet
    SourceAddress           : 2001:4898:d8:33:81e8:7b49:8bf5:8710
    NetRoute (NextHop)      : fe80::200:5eff:fe00:203
    TcpTestSucceeded        : True

    This command tests TCP connectivity to a default server and sets the InformationLevel parameter to Detailed.
#>

Get-help -Name Test-NetConnection -Full
Get-help -Name Test-NetConnection -Online

一段时间以来,已经发布了该用例的代码。

Test-NetworkPort 1.0 用于测试是否打开TCP或UDP端口的脚本。