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

时间:2012-03-05 11:44:16

标签: powershell powershell-v2.0

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

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

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

10 个答案:

答案 0 :(得分:45)

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

例如:

Test-NetConnection -Port 53 -ComputerName LON-DC1

答案 1 :(得分:37)

我在几个方面改进了Salselvaprabu的答案:

  1. 它现在是一个功能 - 您可以随时添加您的powershell配置文件并随时使用
  2. 它可以接受主机作为主机名或IP地址
  3. 如果主机或端口不可用,则不再有例外 - 只是文本
  4. 这样称呼:

    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
    }
    

答案 2 :(得分: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. "
    }

答案 3 :(得分:11)

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

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

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

答案 4 :(得分:7)

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

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

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

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

答案 5 :(得分: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
}

答案 6 :(得分:4)

如果您使用的是旧版本的Powershell,其中Test-NetConnection不可用,则此处为主机名和#34; my.hostname&#34;和港口&#34; 123&#34;:

<form name="form1" method="post" action="index2.jsp">
<input type="checkbox" name="check">

返回OK或错误消息。

答案 7 :(得分:0)

mshutov&amp; 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

}

答案 8 :(得分:0)

将其煮成一个衬里设置变量&#34; $ port389Open&#34;对于真或假 - 它快速且易于复制以获得端口列表

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
}

答案 9 :(得分:-1)

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

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