Opening up a port with powershell

前端 未结 2 1953
独厮守ぢ
独厮守ぢ 2020-12-14 10:09

On Machine A I am running a port scanner. On Machine B I would like to open and close ports in an organized fashion. I am hoping to do all of this

2条回答
  •  萌比男神i
    2020-12-14 11:00

    Avoid COM if possible. You can use TcpListener to open a port:

    $Listener = [System.Net.Sockets.TcpListener]9999;
    $Listener.Start();
    #wait, try connect from another PC etc.
    $Listener.Stop();
    

    If you happen to miss a Stop command during debugging - just close and re-open the application from where you opened the socket - hanging port should be cleared. In my case it was PowerGUI script editor.

    Then use TcpClient to check it.

    (new-object Net.Sockets.TcpClient).Connect($host, $port)
    

    If you cannot connect, means the firewall is blocking it.

    EDIT: To print a message when connection is received, you should be able to use this code (based on this article from MSDN):

    #put this code in between Start and Stop calls.
    while($true) 
    {
        $client = $Listener.AcceptTcpClient();
        Write-Host "Connected!";
        $client.Close();
    }
    

提交回复
热议问题