我尝试使用powershell检查端口是否打开,如下所示。
(new-object Net.Sockets.TcpClient).Connect("10.45.23.109", 443)此方法有效,但输出不是用户友好的。这意味着如果没有错误,那么它就有访问权。有没有办法检查是否成功,并显示一些消息,如“端口443可操作”?
发布于 2012-03-08 15:06:41
实际上,谢伊·列维的回答几乎是正确的,但正如我在他的评论专栏中提到的那样,我遇到了一个奇怪的问题。因此,我将命令拆分为两行,它可以很好地工作。
$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. "
}发布于 2014-09-19 07:33:46
如果你运行的是Windows8/ Windows Server2012或更新版本,你可以在PowerShell中使用Test-NetConnection命令。
例如:
Test-NetConnection -Port 53 -ComputerName LON-DC1发布于 2014-03-21 16:02:50
我从几个方面改进了Salselvaprabu的回答:
这样叫它:
Test-Port example.com 999
Test-Port 192.168.0.1 80function 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
}https://stackoverflow.com/questions/9566052
复制相似问题