views:

814

answers:

3

Ok, it's little convoluted.

I am trying to write a script to automate telneting to a machine, execute few commands, look at the output in the telnet window, based on the output, send few more commands.

Thanks for any help

A: 

what's the server side? unix? osx? windows+telnetd? powershell v1 or v2? can you install stuff on the remote side? the client side?

x0n
What is the script to be written in ?
Romain Hippeau
@Romain - the title says it all: powershell.
x0n
powershell v2. I am writing the powershell script on a windows machine. Remote side can be, linux, windows. I can't install new stuff on the remote site
Guru Je
+1  A: 

Rather than try to automate a telnet executable, just create the socket and issue the commands, read them back, and make decisions based on that. Here is an oversimplified example connecting to my local web server:

function test() {
  $msg = [System.Text.Encoding]::ASCII.GetBytes("GET / HTTP/1.0`r`nHost: localhost`r`n`r`n")
  $c = New-Object System.Net.Sockets.TcpClient("localhost", 80)
  $str = $c.GetStream()
  $str.Write($msg, 0, $msg.Length)
  $buf = New-Object System.Byte[] 4096
  $count = $str.Read($buf, 0, 4096)
  [System.Text.Encoding]::ASCII.GetString($buf, 0, $count)
  $str.Close()
  $c.Close()
}

Obviously you would need to change it from port 80, and pass a username/password instead of a web request header... but this should be enough to get you started.

Goyuix
Thanks for the sample. I am very new to powershell. I tried few things based to the above code but things didn't work, but I must be missing something. Here what I tring to do. telnet <ip> portnum // wait until the screen says BIOS START <send following sequence> "esc crtl [" if I can do the above, rest of the script becomes quite easy. Again thanks for the input, I'll keep trying based on the above example.
Guru Je
wait, you're trying to telnet into a remote machine to capture the boot sequence?! tell me I'm wrong...
x0n
no, telnet captures the output of a development board through a serial port on the remote machine. I have anthor telnet session into the remote machine to send commands to the development board. So the idea is to capture the output from the first telnet session, figureout what is the state of the development board, send more commands to the development board through the second telnet window.
Guru Je
+2  A: 

I wouldn't do anything with sockets here because you are going to need to implement at least parts of the telnet spec. If I remember, that spec is a bit funny. But there are some .NET telnet implementations listed here: http://stackoverflow.com/questions/390188/c-telnet-library that you can probably adapt or use directly from powershell in the same way that Goyuix is using the socket code in his answer.

jeffesp