Skip to content

Instantly share code, notes, and snippets.

@Ertavf
Created May 5, 2023 20:41
Show Gist options
  • Save Ertavf/d3175e9f9670e308a71b5dd12c7e1c3a to your computer and use it in GitHub Desktop.
Save Ertavf/d3175e9f9670e308a71b5dd12c7e1c3a to your computer and use it in GitHub Desktop.
opening-up-a-port-with-powershell.ps1
# https://stackoverflow.com/questions/13129060/opening-up-a-port-with-powershell
Clear-Host; $VerbosePreference="Continue"; $Port=23
$EndPoint=[System.Net.IPEndPoint]::new([System.Net.IPAddress]::Parse("0.0.0.0"),$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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment