PowerShell Test NetConnection (Check is Port available)


  1. 說明
    1. Test-NetConnection
    2. System.Net.Sockets.TcpClient
    3. NMAP
  2. 檢查伺服器所有服務的 Port
    1. PowerShell
  3. 相關連結
  4. 參考資料

筆記如何使用 PowerShell 檢查特定 Port 是否提供服務。

logo

說明

Test-NetConnection

Test-NetConnection 是 Test-Connection 以及 Ping 的後繼者,可以指定 Port 對遠端 Host 進行連線測試。

Test-NetConnection ptt.cc -port 23
ComputerName     : pttcc
RemoteAddress    : 140.112.172.5
SourceAddress    : 127.0.0.1
TcpTestSucceeded : True
Test-NetConnection www.ptt.cc -port 443
ComputerName     : www.ptt.cc
RemoteAddress    : 104.21.235.87
RemotePort       : 443
InterfaceAlias   : 乙太網路
SourceAddress    : 127.0.0.1
TcpTestSucceeded : True

如果 Port 沒有回應則會顯示如下訊息:

Test-NetConnection www.ptt.cc -port 23
警告: TCP connect to (104.21.235.88 : 23) failed
警告: TCP connect to (104.21.235.87 : 23) failed
ComputerName           : www.ptt.cc
RemoteAddress          : 104.21.235.88
RemotePort             : 23
InterfaceAlias         : 乙太網路
SourceAddress          : 127.0.0.1
PingSucceeded          : True
PingReplyDetails (RTT) : 40 ms
TcpTestSucceeded       : False

System.Net.Sockets.TcpClient

此外也可以使用 .NET 的 TcpClient 類別測試 Port。

New-Object System.Net.Sockets.TcpClient("www.ptt.cc", 443)

NMAP

可以由 Client 端使用 NMAP 批次檢查。

檢查伺服器所有服務的 Port

netstat -na | findstr LISTENING

PowerShell

Get-NetTCPConnection -State Listen

相關連結

PowerShell 使用者不能錯過的 5 個技巧

Powershell 使用物件與資料結構 (Array, Hash)

PowerShell 常用指令筆記

參考資料

MSDocs - Invoke-WebRequest