惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss
J
Java Code Geeks
M
MIT News - Artificial intelligence
F
Fortinet All Blogs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
Microsoft Security Blog
Microsoft Security Blog
N
Netflix TechBlog - Medium
G
Google Developers Blog
L
LangChain Blog
腾讯CDC
大猫的无限游戏
大猫的无限游戏
U
Unit 42
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
The GitHub Blog
The GitHub Blog
博客园_首页
GbyAI
GbyAI

wentao's blog

解决armbian更新报不能验证个别公钥 nyagos增加zoxide的支持 快速查找PowerShell的历史命令 denote wezterm的workspace配置 PSReadLine最强PowerShell模块 读《万千微尘纷坠心田》 Emacs添加腾讯会议连接 一个新的终端模拟器WezTerm
利用PowerShell来进行端口连通性测试
wentao写点代码,解决点问题。 douban github twitter Spotify telegram · 2022-07-17 · via wentao's blog

一般情况下在是使用 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
	}
}