title: How to telnet programmatically and issue commands via a TCP socket?
body: <p>I am working on an application in C for an embedded Linux system on a serial device server. I need to access the system's own shell that you can telnet to and has a bunch of custom command line interface commands that can be executed at the shell prompt.</p>
  
  <p>An engineer working for the manufacturer of the device said the only way to programatically issue these command line interface commands is via a telnet client that logs into the shell.</p>
  
  <p>So, within my application, I want to have the device server telnet to itself so that it can issue some commands to itself via its shell. Before I do the C implementation, I figured I'd just try to open a socket via IRB and try to get the commands working that way first. The actual telnet session looks like this:</p>
  
  <pre><code>login: admin
  password: password
  
  prompt# set watchdog off
  prompt# save
  Save config to flash ROM y/n
  y    
  </code></pre>
  
  <p>Below is the simple script I'm running in IRB to see if I can emulate the above telnet session via a TCP socket since that's how I'll implement in C on Linux:</p>
  
  <pre><code>require 'socket'
  @ip = 'xxx.xxx.xxx.xxx'
  @enter = "\n"
  @sock = TCPSocket.open(@ip,23)
  @ret = @sock.write("admin" + @enter)
  puts @ret.to_s
  sleep(1)      
  @ret = @sock.write("password" + @enter)
  puts @ret.to_s
  puts @sock.read(1)
  sleep(2)
  @ret = @sock.write("set watchdog off" + @enter)
  puts @ret.to_s
  puts @sock.read(1)
  sleep(1)
  @ret = @sock.write("save" + @enter)
  puts @ret.to_s
  puts @sock.read(1)
  sleep(1)
  @ret = @sock.write("y")
  puts @ret.to_s
  puts @sock.read(1)
  sleep(1)
  
  @sock.close
  </code></pre>
  
  <p>Opening, writing to and reading from sockets in C are no problem for me and I do it a lot already in my application so I already have easy functions to do those things ready to go. My question is what strings should I be writing to the sockets to emulate let's say pressing the enter key after I type something at a prompt? "\n" or "\x0a" were not working. OR could I be using a linux C library that'll make this way easier for me?</p>