如何检查网络端口访问并显示有用的消息?

问题描述 投票:24回答:10

我试图检查端口是否打开使用PowerShell,如下所示。

(new-object Net.Sockets.TcpClient).Connect("10.45.23.109", 443)

此方法有效,但输出不是用户友好的。这意味着如果没有错误,那么它就具有访问权限。有没有办法检查成功并显示一些消息,如“端口443是否可操作”?

powershell powershell-v2.0
10个回答
46
投票

如果您运行的是Windows 8 / Windows Server 2012或更高版本,则可以在PowerShell中使用Test-NetConnection命令。

例如:

Test-NetConnection -Port 53 -ComputerName LON-DC1

-1
投票

扫描关闭端口时,它会长时间无响应。将fqdn解析为ip时似乎更快:

[System.Net.Dns]::GetHostAddresses("www.msn.com").IPAddressToString

39
投票

我以几种方式改进了Salselvaprabu的答案:

  1. 它现在是一个功能 - 您可以放入您的powershell配置文件并随时使用
  2. 它可以接受主机作为主机名或IP地址
  3. 如果主机或端口不可用,则不再需要豁免 - 只需文本

像这样称呼它:

Test-Port example.com 999
Test-Port 192.168.0.1 80

function Test-Port($hostname, $port)
{
    # This works no matter in which form we get $host - hostname or ip address
    try {
        $ip = [System.Net.Dns]::GetHostAddresses($hostname) | 
            select-object IPAddressToString -expandproperty  IPAddressToString
        if($ip.GetType().Name -eq "Object[]")
        {
            #If we have several ip's for that address, let's take first one
            $ip = $ip[0]
        }
    } catch {
        Write-Host "Possibly $hostname is wrong hostname or IP"
        return
    }
    $t = New-Object Net.Sockets.TcpClient
    # We use Try\Catch to remove exception info from console if we can't connect
    try
    {
        $t.Connect($ip,$port)
    } catch {}

    if($t.Connected)
    {
        $t.Close()
        $msg = "Port $port is operational"
    }
    else
    {
        $msg = "Port $port on $ip is closed, "
        $msg += "You may need to contact your IT team to open it. "                                 
    }
    Write-Host $msg
}

14
投票

实际上,Shay levy的答案几乎是正确的,但我在他的评论栏中提到了一个奇怪的问题。所以我将命令分成两行,它工作正常。

$Ipaddress= Read-Host "Enter the IP address:"
$Port= Read-host "Enter the port number to access:"

$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)
    if($t.Connected)
    {
        "Port $Port is operational"
    }
    else
    {
        "Port $Port is closed, You may need to contact your IT team to open it. "
    }

12
投票

您可以检查Connected属性是否设置为$ true并显示友好消息:

    $t = New-Object Net.Sockets.TcpClient "10.45.23.109", 443 

    if($t.Connected)
    {
        "Port 443 is operational"
    }
    else
    {
        "..."
    }

7
投票

使用最新版本的PowerShell,有一个新的cmdlet Test-NetConnection。

实际上,此cmdlet可以ping一个端口,如下所示:

Test-NetConnection -ComputerName <remote server> -Port nnnn

我知道这是一个老问题,但是如果你点击这个页面(正如我所做的那样)寻找这些信息,这个添加可能会有所帮助!


4
投票

我试图改进mshutov的建议。我添加了将输出用作对象的选项。

 function Test-Port($hostname, $port)
    {
    # This works no matter in which form we get $host - hostname or ip address
    try {
        $ip = [System.Net.Dns]::GetHostAddresses($hostname) | 
            select-object IPAddressToString -expandproperty  IPAddressToString
        if($ip.GetType().Name -eq "Object[]")
        {
            #If we have several ip's for that address, let's take first one
            $ip = $ip[0]
        }
    } catch {
        Write-Host "Possibly $hostname is wrong hostname or IP"
        return
    }
    $t = New-Object Net.Sockets.TcpClient
    # We use Try\Catch to remove exception info from console if we can't connect
    try
    {
        $t.Connect($ip,$port)
    } catch {}

    if($t.Connected)
    {
        $t.Close()
        $object = [pscustomobject] @{
                        Hostname = $hostname
                        IP = $IP
                        TCPPort = $port
                        GetResponse = $True }
        Write-Output $object
    }
    else
    {
        $object = [pscustomobject] @{
                        Computername = $IP
                        TCPPort = $port
                        GetResponse = $False }
        Write-Output $object

    }
    Write-Host $msg
}

4
投票

如果您使用的是旧版本的Powershell,其中Test-NetConnection不可用,则以下是主机名“my.hostname”和端口“123”的单行:

$t = New-Object System.Net.Sockets.TcpClient 'my.hostname', 123; if($t.Connected) {"OK"}

返回OK或错误消息。


0
投票

mshutov和Salselvaprabu的精彩回答。我需要一些更强大的东西,并检查所提供的所有IP地址,而不是只检查第一个。

我还想复制一些参数名称和功能而不是Test-Connection功能。

此新功能允许您设置重试次数的计数,以及每次尝试之间的延迟。请享用!

function Test-Port {

    [CmdletBinding()]
    Param (
        [string] $ComputerName,
        [int] $Port,
        [int] $Delay = 1,
        [int] $Count = 3
    )

    function Test-TcpClient ($IPAddress, $Port) {

        $TcpClient = New-Object Net.Sockets.TcpClient
        Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}

        If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
        Return $False

    }

    function Invoke-Test ($ComputerName, $Port) {

        Try   { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString } 
        Catch { Return $False }

        [array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
        If ($Results -contains $True) { Return $True } Else { Return $False }

    }

    for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
    {
        if ($i -ge $Count) {
            Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
            Return $false
        }

        Write-Warning "Port $Port not open, retrying..."
        Sleep $Delay
    }

    Return $true

}

0
投票

把它煮成一个衬里将变量“$ port389Open”设置为True或false - 它快速且易于复制以获取端口列表

try{$socket = New-Object Net.Sockets.TcpClient($ipAddress,389);if($socket -eq $null){$Port389Open = $false}else{Port389Open = $true;$socket.close()}}catch{Port389Open = $false}

如果你想真的疯了,你可以归还整个阵列 -

Function StdPorts($ip){
    $rst = "" |  select IP,Port547Open,Port135Open,Port3389Open,Port389Open,Port53Open
    $rst.IP = $Ip
    try{$socket = New-Object Net.Sockets.TcpClient($ip,389);if($socket -eq $null){$rst.Port389Open = $false}else{$rst.Port389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port389Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,53);if($socket -eq $null){$rst.Port53Open = $false}else{$rst.Port53Open = $true;$socket.close();$ipscore++}}catch{$rst.Port53Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,3389);if($socket -eq $null){$rst.Port3389Open = $false}else{$rst.Port3389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port3389Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,547);if($socket -eq $null){$rst.Port547Open = $false}else{$rst.Port547Open = $true;$socket.close();$ipscore++}}catch{$rst.Port547Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,135);if($socket -eq $null){$rst.Port135Open = $false}else{$rst.Port135Open = $true;$socket.close();$SkipWMI = $False;$ipscore++}}catch{$rst.Port135Open = $false}
    Return $rst
}
© www.soinside.com 2019 - 2024. All rights reserved.