Powershell篇章端口监测(一)
参考博客:blog.csdn.net/m0_48983233/article/...
方法命令行层面
netstat -ano | find "端口号"
netstat -ano | findstr 端口号
区别:find端口号需要是字符串,findstr后面可以直接跟端口号,也可以跟字符串
代码层面 编写
function Test-Port
{
Param([string]$ComputerName,$port = 5985,$timeout = 1000)
try
{
$tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
$iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
if(!$wait)
{
$tcpclient.Close()
return $false
}
else
{
# Close the connection and report the error if there is one
$null = $tcpclient.EndConnect($iar)
$tcpclient.Close()
return $true
}
}
catch
{
$false
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接