I have tried to get PowerShell automation for Telnet connecting to Windows Server 2012 R2, Ubuntu 16.04 and Windows XP SP3 and all servers are throwing junk characters as output.
I was going through rfc854 but I could not get this done.
Could you please help me on how to resolve this issue.
Below code would try to connect Telnet server with credentials and output dir list.
Code
param (
[string] $terminalServer = "192.168.19.131",
[int] $port = 23,
[string] $username = "username",
[string] $password = "password",
[int] $commandDelay = 1000,
[string] $output = ""
)
function GetOutput {
## Create a buffer to receive the response
$buffer = new-object System.Byte[] 1024
$encoding = new-object System.Text.AsciiEncoding
$outputBuffer = ""
$foundMore = $false
## Read all the data available from the stream, writing it to the
## output buffer when done.
do {
## Allow data to buffer for a bit
start-sleep -m 1000
## Read what data is available
$foundmore = $false
$stream.ReadTimeout = 2000
do {
try {
$read = $stream.Read($buffer, 0, 1024)
if($read -gt 0) {
$foundmore = $true
$outputBuffer += ($encoding.GetString($buffer, 0, $read))
}
} catch { $foundMore = $false; $read = 0 }
} while($read -gt 0)
} while($foundmore)
$outputBuffer
}
$output = ""
write-host "Connecting to $terminalServer on port $port..."
trap { Write-Error "Could not connect to the server: $_"; exit }
$socket = new-object System.Net.Sockets.TcpClient($terminalServer, $port)
write-host "Connected. `n"
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter $stream
## Receive the output that has buffered so far
$SCRIPT:output += GetOutput
$writer.WriteLine($username)
$writer.Flush()
Start-Sleep -m $commandDelay
$SCRIPT:output += GetOutput
$writer.WriteLine($password)
$writer.Flush()
Start-Sleep -m $commandDelay
$SCRIPT:output += GetOutput
$writer.WriteLine("dir")
$writer.Flush()
Start-Sleep -m $commandDelay
$SCRIPT:output += GetOutput
$writer.WriteLine("exit")
$writer.Flush()
Start-Sleep -m $commandDelay
## Close the streams
$writer.Close()
$stream.Close()
write-host "All streams are closed. The final output is"
$output
Output
D:\Tools\T24\PowerShell>powershell .\telnet_test.ps1
Connecting to 192.168.19.131 on port 23...
Connected.
All streams are closed. The final output is
??%??????'???? ??