PoshCode Archive  Artifact [19657dc56c]

Artifact 19657dc56caed9b0113bb313a8d5621aac508942b909d2b903a795a3506d9ec8:

  • File scriptable-telnet-client.ps1 — part of check-in [366f8b752e] at 2018-06-10 14:02:10 on branch trunk — I wrote this a while back to be able to automate stuff on a hp san and ilo. It’s pretty much mritten ad-hoc so please feel free to improve on it. Anyway, might be useful for someone out there. The function send-command logs on to a telnet server and executes the piped in commands. (user: David Sjstrand size: 2381)

# encoding: ascii
# api: powershell
# title: scriptable telnet client
# description: I wrote this a while back to be able to automate stuff on a hp san and ilo. It’s pretty much mritten ad-hoc so please feel free to improve on it. Anyway, might be useful for someone out there. The function send-command logs on to a telnet server and executes the piped in commands.
# version: 0.1
# type: function
# author: David Sjstrand
# license: CC0
# function: read-stream
# x-poshcode-id: 5828
# x-derived-from-id: 5829
# x-archived: 2016-07-01T08:52:27
# x-published: 2016-04-16T08:12:00
#
# Example:
# Get-content commands.txt | send-command -hostname telnetserver.somewhere.com -user someuser -password somepassword
#
function read-stream ([Parameter(Posistion=0,Mandatory=$true)][validatenotnull()]
		[System.Net.Sockets.NetworkStream]$stream,
		[String]$expect = "")
{
	$buffer = new-object system.byte[] 1024
	$enc = new-object system.text.asciiEncoding

	## Read all the data available from the stream, writing it to the 
	## screen when done.

	## Allow data to buffer
	start-sleep -m 100
	$output = ""
	while($stream.DataAvailable -or $output -notmatch $expect)
	{   
		$read = $stream.Read($buffer, 0, 1024)    
		$output = "$output$($enc.GetString($buffer, 0, $read))"
		## Allow data to buffer for a bit 
		start-sleep -m 100
	}
	$output.split("`n")
}

function send-command ([parameter(position=0,Mandatory=$true)][validatenotnull()]
		[String]$hostname,
	[parameter(position=1,Mandatory=$true)][validatenotnull()]
		[String]$User,
	[parameter(position=2,Mandatory=$true)][validatenotnull()]
		[String]$Password, 
	[parameter(position=3,Mandatory=$true,valuefrompipeline=$true)][validatenotnull()]
		[String]$InputObject,
		[string]$Expect = "")
{
	begin
	{
		
		$sock = new-object system.net.sockets.tcpclient($hostname,23)
		$str = $sock.GetStream()
		$wrt = new-object system.io.streamwriter($str)
		
		read-stream($str)
		$wrt.writeline($user)
		$wrt.flush()
		read-stream($str)
		$wrt.writeline($password)
		$wrt.flush()
		read-stream($str, $expect)
	}
	process
	{
		$wrt.writeline($InputObject)
		$wrt.flush()
		read-stream($str, $expect)
	}
	end
	{
		$wrt.writeline("exit")
		$wrt.flush()
		read-stream($str)

		## Close the streams 
		$wrt.Close()
		$str.Close()
		$sock.close()
	}
}