Cool PowerShell Script Replicates Telnet

Lee Holmes has a cool script to reproduce telnet-like functionality via the TcpClient object in PowerShell.

## Connect-Computer.ps1 
## Interact with a service on a remote TCP port 
param( 
    [string] $remoteHost = "localhost", 
    [int] $port = 23
     ) 

try
{
    ## Open the socket, and connect to the computer on the specified port 
    write-host "Connecting to $remoteHost on port $port" 
    $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port) 
    if($socket -eq $null) { return; } 

    $stream = $socket.GetStream() 
    $writer = new-object System.IO.StreamWriter($stream) 

    $buffer = new-object System.Byte[] 1024 
    $encoding = new-object System.Text.AsciiEncoding 

    while($true) 
    { 
       ## Allow data to buffer for a bit 
       start-sleep -m 500 

       ## Read all the data available from the stream, writing it to the 
       ## screen when done. 
       while($stream.DataAvailable)  
       {  
          $read = $stream.Read($buffer, 0, 1024)    
          write-host -n ($encoding.GetString($buffer, 0, $read))  
       } 

       ## Read the user's command, quitting if they hit ^D 
       $command = read-host 
      
       ## Write their command to the remote host      
       $writer.WriteLine($command) 
       $writer.Flush() 
    } 
}
finally
{
    ## Close the streams 
    $writer.Close() 
    $stream.Close()
}

This solves the problem of telnet.exe crashing conhost.exe when using Console2.

Update

I tweaked Lee’s code to use try/finally which obviates the need for a special escape sequence to clean up the TCP resources.

About these ads

3 Responses to Cool PowerShell Script Replicates Telnet

  1. vivek says:

    I am getting unwanted characters along with the ouput:
    Before the first command is inserted i, i am getting these symbols:

    ??☺??☺??▼??♥??♥??↑
    ←[2K←[D←[D←[D←[D←[D←[D←[D←[D←

    Please help: how can i stop getting this weird symbols

  2. Pingback: Backup Network Configuration with PowerShell | System Center ZA

  3. Pingback: Backup Network Configuration with PowerShell | System Center Guy ZA

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 84 other followers

%d bloggers like this: