利用PowerShell来进行端口连通性测试

2022-07-17 • 预计阅读时间 1 分钟

一般情况下在是使用 telnet 来做网络连通性的测试. PowerShell 也可以实现类似的功能.而且由于本身和 .Net 的关系,还可以通过 .Net 的支持来完成.

原生的方案:Test-Connection

连接成功

Measure-Command {Test-NetConnection wentao.org -Port 80} | % TotalSeconds

连接失败

Measure-Command {Test-NetConnection wentao.2org -Port 80} | % TotalSeconds

使用System.Net.Sockets.TcpClient的方案

  function Test-Port {
	[CmdletBinding()]
	param (
		[Parameter(ValueFromPipeline = $true, HelpMessage = 'Could be suffixed by :Port')]
		[String[]]$ComputerName,

		[Parameter(HelpMessage = 'Will be ignored if the port is given in the param ComputerName')]
		[Int]$Port = 5985,

		[Parameter(HelpMessage = 'Timeout in millisecond. Increase the value if you want to test Internet resources.')]
		[Int]$Timeout = 1000
	)

	begin {
		$result = [System.Collections.ArrayList]::new()
	}

	process {
		foreach ($originalComputerName in $ComputerName) {
			$remoteInfo = $originalComputerName.Split(":")
			if ($remoteInfo.count -eq 1) {
				# In case $ComputerName in the form of 'host'
				$remoteHostname = $originalComputerName
				$remotePort = $Port
			} elseif ($remoteInfo.count -eq 2) {
				# In case $ComputerName in the form of 'host:port',
				# we often get host and port to check in this form.
				$remoteHostname = $remoteInfo[0]
				$remotePort = $remoteInfo[1]
			} else {
				$msg = "Got unknown format for the parameter ComputerName: " `
					+ "[$originalComputerName]. " `
					+ "The allowed formats is [hostname] or [hostname:port]."
				Write-Error $msg
				return
			}

			$tcpClient = New-Object System.Net.Sockets.TcpClient
			$portOpened = $tcpClient.ConnectAsync($remoteHostname, $remotePort).Wait($Timeout)

			$null = $result.Add([PSCustomObject]@{
				RemoteHostname       = $remoteHostname
				RemotePort           = $remotePort
				PortOpened           = $portOpened
				TimeoutInMillisecond = $Timeout
				SourceHostname       = $env:COMPUTERNAME
				OriginalComputerName = $originalComputerName
				})
		}
	}

	end {
		return $result
	}
}
devpowershell

wentao

写点代码,解决点问题。

wezterm的workspace配置