Sam*_*abu 28 powershell powershell-2.0
我试图检查端口是否打开使用PowerShell,如下所示.
(new-object Net.Sockets.TcpClient).Connect("10.45.23.109", 443)
Run Code Online (Sandbox Code Playgroud)
此方法有效,但输出不是用户友好的.这意味着如果没有错误,那么它就具有访问权限.有没有办法检查成功并显示一些消息,如"端口443是否可操作"?
Sim*_*urk 52
如果您运行的是Windows 8/Windows Server 2012或更高版本,则可以在PowerShell中使用Test-NetConnection命令.
例如: __CODE__
msh*_*tov 42
我以几种方式改进了Salselvaprabu的答案:
像这样称呼它:
Test-Port example.com 999
Test-Port 192.168.0.1 80
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*abu 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. "
}
Run Code Online (Sandbox Code Playgroud)
Sha*_*evy 13
您可以检查Connected属性是否设置为$ true并显示友好消息:
$t = New-Object Net.Sockets.TcpClient "10.45.23.109", 443
if($t.Connected)
{
"Port 443 is operational"
}
else
{
"..."
}
Run Code Online (Sandbox Code Playgroud)
使用最新版本的PowerShell,有一个新的cmdlet Test-NetConnection.
实际上,此cmdlet可以ping一个端口,如下所示:
Test-NetConnection -ComputerName <remote server> -Port nnnn
Run Code Online (Sandbox Code Playgroud)
我知道这是一个老问题,但如果你打这个页面(像我一样)在寻找这个信息,这除了可能会有所帮助!
| 归档时间: |
|
| 查看次数: |
147896 次 |
| 最近记录: |