测试TCP端口是否在未连接的情况下打开

时间:2019-10-10 09:49:12

标签: .net powershell powershell-2.0 tcpclient

有人要求我将使用cursor的bash脚本转换为PowerShell。

This site告诉我nc -z测试端口是否“未连接”打开。有什么方法可以使用.Net做到这一点?

其他信息

通常要测试端口是否打开,我会用.Net的nc -z创建连接;如果连接成功,我也会报告所有问题。以下是MVE:

TcpClient

但是,虽然不发送任何数据,但它确实可以连接。

可能是$isConnected = $false $client = New-Object -TypeName 'System.Net.Sockets.TcpClient' try { $client.Connect($host, $port) $isConnected = $client.Connected $client.GetStream().Close(); # handle bug in .net 1.1 $client.Close(); } catch { $isConnected = $false } finally { if ($client.Dispose) {$client.Dispose()} # dispose method not available in all versions, so check before calling } 的描述具有误导性/只是意味着没有发送数据...我两种方式都无法找到确认。

2 个答案:

答案 0 :(得分:1)

使用 Test-NetConnection

Test-NetConnection -ComputerName $host -Port $port

输出看起来像这样:

ComputerName     : [computername]
RemoteAddress    : [remoteipaddress]
RemotePort       : 80
InterfaceAlias   : Ethernet 2
SourceAddress    : [sourceipaddress]
TcpTestSucceeded : True

Test-NetConnection Documentation

使用Tcp客户端类(.Net):

 New-Object System.Net.Sockets.TcpClient($ip, $port)

输出:

Client              : System.Net.Sockets.Socket
Available           : 0
Connected           : True
ExclusiveAddressUse : False
ReceiveBufferSize   : 65536
SendBufferSize      : 64512
ReceiveTimeout      : 0
SendTimeout         : 0
LingerState         : System.Net.Sockets.LingerOption
NoDelay             : False

Tcp Client Documentation

答案 1 :(得分:0)

看哪。如果只需要布尔值而不是对象,请添加-Quiet标志。

Test-NetConnection $Address -Port $TcpPort

https://docs.microsoft.com/en-us/powershell/module/nettcpip/test-netconnection?view=win10-ps

相关问题