powershell
NetFramework,  Powershell

Telnet script

There are situations when you need to check the availability of a particular port. Send commands and get an answer. This script can be used as a complete replacement for telnet. Only if telnet cannot be mistaken when entering a command, then it is possible here. It can also be easily edited and used for automatic hosts querying.


function ReadStream {

param(
        [Parameter(Mandatory=$true, Position=0, HelpMessage='TCP Socket')] 
        [Alias("s")] 
        [ValidateScript({$_.GetType().name -eq 'TcpClient'})]
        $Socket              
       ) 
        
begin {
$Bytes = New-Object System.Byte[] $Socket.ReceiveBufferSize
$Encoding = New-Object System.Text.AsciiEncoding
}
process {

if (!($socket.Connected)) {
return "Socket not connected"
break
}
$timer = 0
    while (-not($Socket.GetStream().DataAvailable)) {
        sleep -m 10
        $timer++
        if ($timer -gt 500) {return "No data recieved"
        break}
    }
    while($Socket.GetStream().DataAvailable) {
    try {$Read = $stream.Read($Bytes, 0, $Socket.ReceiveBufferSize )
}
catch {
return "Error occurred while reading stream"
break
}
	    return ($Encoding.GetString($Bytes, 0, $Read)).trim()
    }
}
}

# SELECT HOST TO QUERY
$RemoteHost = "173.194.73.27"
$Port = 25

try { 
$Socket = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)}
catch {
if ($Error.exception -match "A connection attempt failed") {
write-host "Error connecting to host $RemoteHost"
}
break
}

$stream = $Socket.GetStream()

$Writer = New-Object System.IO.StreamWriter($Stream)

#$Reader = New-Object System.IO.StreamReader($Stream)

Start-Sleep 1

ReadStream $Socket


while ($Socket.Connected) {
$command = Read-Host

if ($command -match 'quit' ){

$Writer.WriteLine($command)
try {
$Writer.Flush()
}
catch {
Write-host "Error writing to stream"
$Writer.Dispose()
$Writer.close()
$Socket.Dispose()
$Socket.close()
break
}
ReadStream $Socket

Write-host "Closing connection"
$Writer.Dispose()
$Writer.close()
$Socket.Dispose()
$Socket.close()
break
}

If ($command) {
$Writer.WriteLine($command)
try {
$Writer.Flush()
}
catch {
Write-host "Error writing to stream"
$Writer.Dispose()
$Writer.close()
$Socket.Dispose()
$Socket.close()
break
}
}

write-host $stream.DataAvailable
ReadStream $Socket
}

Leave a Reply