开Machine A
我正在运行端口扫描程序。在Machine B
我想以有组织的方式打开和关闭端口。我希望通过powershell完成所有这些工作。
我发现THIS脚本要在Machine B
上运行,但是当从Machine A
扫描同一个端口时,它仍然表示它已关闭。
你们中的任何人都知道如何在Machine B
答案 0 :(得分:17)
尽可能避免使用COM。您可以使用TcpListener打开端口:
$Listener = [System.Net.Sockets.TcpListener]9999;
$Listener.Start();
#wait, try connect from another PC etc.
$Listener.Stop();
如果您在调试期间碰巧错过了Stop
命令 - 只需关闭并重新打开您打开套接字的应用程序 - 应该清除挂起端口。就我而言,它是PowerGUI script editor
。
然后使用TcpClient进行检查。
(new-object Net.Sockets.TcpClient).Connect($host, $port)
如果无法连接,则表示防火墙正在阻止它。
编辑:要在收到连接时打印邮件,您应该可以使用此代码(基于this article from MSDN):
#put this code in between Start and Stop calls.
while($true)
{
$client = $Listener.AcceptTcpClient();
Write-Host "Connected!";
$client.Close();
}
答案 1 :(得分:0)
我需要的东西不仅要确认端口是开放的,而且还要响应。因此,这是我的超级基本非远程登录服务器。
Clear-Host; $VerbosePreference="Continue"; $Port=23
$EndPoint=[System.Net.IPEndPoint]::new([System.Net.IPAddress]::Parse("<ip address>"),$Port)
$Listener=[System.Net.Sockets.TcpListener]::new($EndPoint)
$KeepListening=$true
while ($KeepListening) {
$Listener.Start()
while (!$Listener.Pending) { Start-Sleep -Milliseconds 100 }
$Client=$Listener.AcceptTcpClient()
Write-Output "Incoming connection logged from $($Client.Client.RemoteEndPoint.Address):$($Client.Client.RemoteEndPoint.Port)"
$Stream=$Client.GetStream()
$Timer=10; $Ticks=0; $Continue=$true
$Response=[System.Text.Encoding]::UTF8.GetBytes("I see you. I will die in $($Timer.ToString()) seconds.`r`nHit <space> to add another 10 seconds.`r`nType q to quit now.`r`nType x to terminate listener.`r`n`r`n")
$Stream.Write($Response,0,$Response.Length)
$StartTimer=(Get-Date).Ticks
while (($Timer -gt 0) -and $Continue) {
if ($Stream.DataAvailable) {
$Buffer=$Stream.ReadByte()
Write-Output "Received Data: $($Buffer.ToString())"
if ($Buffer -eq 113) {
$Continue=$false
$Response=[System.Text.Encoding]::UTF8.GetBytes("`r`nI am terminating this session. Bye!`r`n")
}
elseif ($Buffer -eq 32) {
$Timer+=10
$Response=[System.Text.Encoding]::UTF8.GetBytes("`r`nAdding another 10 seconds.`r`nI will die in $($Timer.ToString()) seconds.`r`n")
}
elseif ($Buffer -eq 120) {
$Continue=$false
$KeepListening=$false
$Response=[System.Text.Encoding]::UTF8.GetBytes("`r`nI am terminating the listener. :-(`r`n")
}
else { $Response=[System.Text.Encoding]::UTF8.GetBytes("`r`nI see you. I will die in $($Timer.ToString()) seconds.`r`nHit <space> to add another 10 seconds.`r`nType q to quit this session.`r`nType x to terminate listener.`r`n`r`n") }
$Stream.Write($Response,0,$Response.Length)
}
$EndTimer=(Get-Date).Ticks
$Ticks=$EndTimer-$StartTimer
if ($Ticks -gt 10000000) { $Timer--; $StartTimer=(Get-Date).Ticks }
}
$Client.Close()
}
$Listener.Stop()