21

Machine A正在运行端口扫描程序。OnMachine B我想以有组织的方式打开和关闭端口。我希望通过 powershell 完成所有这些工作。

我发现这个脚本可以运行Machine B但是当从它扫描相同的端口Machine A时仍然说它是关闭的。

你们有谁知道我如何成功打开一个端口Machine B

4

2 回答 2

42

尽可能避免使用 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)

如果无法连接,则表示防火墙正在阻止它。

编辑:要在收到连接时打印一条消息,您应该能够使用此代码(基于MSDN 的这篇文章):

#put this code in between Start and Stop calls.
while($true) 
{
    $client = $Listener.AcceptTcpClient();
    Write-Host "Connected!";
    $client.Close();
}
于 2012-10-29T20:30:24.403 回答
1

我需要的东西不仅能承认端口是开放的,而且还能做出响应。所以,这是我的超级基本的不完全远程登录服务器。

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()
于 2020-12-04T17:07:48.453 回答