tom's blog logo

PowerShell emulate telnet session and test output

Post by Thomas Weaver on January 23, 2012 8:44 pm

Powershell is a very powerful scripting language. In this post I’ll show you a script that can emulate a telnet connection that will automatically enter the commands you pass to it one after the other.

This can be used to monitor certain services such as smtp or even a web server. A second Sript can be used to check a log file for a certain string. If that string isnt present then the monitor is down.

The original TCP connection code was adapted from :

http://brianreiter.org/2011/06/08/cool-powershell-script-replicates-telnet/

Below is the script:

 

 

 

 

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

$TempLogFilePath = "Temp.log"

Start-Transcript -Path "$TempLogFilePath"

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) {
		throw ("Could Not Connect")
	}

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

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

	#Loop through $commands and execute one at a time.

	for($i=0; $i -lt $commands.Count; $i++) { ## 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))
		}

		write-host $commands[$i]
		## Write the command to the remote host
		$writer.WriteLine($commands[$i]) $writer.Flush()
	}

	#runs CheckLogs.ps1 script and sends in the output from the telnet emulation and searches for HTML string
	.\CheckLogs.ps1 -LogFile "$TempLogFilePath" -SearchStrings @('HTML')

	if($LASTEXITCODE -eq 0) {
		# If string wasnt found then an error is thrown and caught
		throw ("Text Not found")
	}

}

catch {

	#When an exception is thrown catch it and output the error.
	#this is also where you would send an email or perform the code you want when its classed as down.

	write-host $error[0]

	$dateTime = get-date

	$errorOccurence = "Error occurred connecting to $remoteHost on $port at $dateTime"

	write-host $errorOccurence
}

finally {
	## Close the streams
	## Cleans everything up.
	$writer.Close()
	$stream.Close()

	stop-transcript
}

The script takes in 3 parameters remoteHost, port and commands. The remoteHost and port are self explanitory the commands is an array of strings that the script will execute on the remote host one at a time. The command and the response is then output to the screen. The transcript-start will output everything written to the console to a file. This file is then sent to .\CheckLogs.ps1 which then checks the file for an array of strings and returns a value of 1 if the string was found or 0 if it wasnt.

This is the CheckLogs.ps1 script:

param([string]$LogFile, [string[]]$SearchStrings)

$Exists = 0

for($i=0; $i -lt $SearchStrings.Count; $i++) {

	if((get-content "$LogFile" | select-string -Quiet -pattern $SearchStrings[$i])) {
		$Exists = 1
	}

}

if($Exists -eq 1) {
	exit 1
}
else {
	exit 0
}

So you can call the script this way:

PS C:\scripts> .\telnet-checker.ps1 -remoteHost 192.168.0.1 -port 80 -commands @(‘GET / HTTP/1.1′,’Connection: Close’, ”, ”)

This will opn a TCP connection on port 80 to 192.168.0.1 and then get the homepage of the web server.

An example of monitoring an SMTP server would be this:

PS C:\scripts> .\telnet-checker.ps1 -remoteHost mail.test.com -port 25 -commands @(‘HELO’, ‘MAIL FROM: test@test.com’, ‘RCPT TO: someone@test.com’, ‘DATA’, ‘SUBJECT: Test’, ”, ‘this is the content’, ”, ‘.’, ”)

Obviously the string passed in to CheckLog.ps1 will be changed to whatever response you are expecting back.

Post a Comment

Your email address will not be published. Required fields are marked *


*


  • curtiss says:

    your ad banner is blocking the ‘view source’ button on the first script.

  • Sorry Curtiss. You can now access the source