telnet connection using PHP

farzad picture farzad · May 25, 2009 · Viewed 77k times · Source

I need to write a PHP script to telnet to a router, run a command and fetch the results. does anyone know a telnet connection library in PHP?

Update: This request (as is obvious) was for a long time ago. In the end I had to write the client library that I needed myself. The code for this library (and many more modules) is open source and available on github. Thanks everyone for your answers.

Answer

131 picture 131 · Apr 14, 2013

using stdin/stream_select & blocking streams gives you a 20 lines telnet like client

<?

$socket = fsockopen("192.168.52.1", 8000);

if(!$socket)return;
stream_set_blocking($socket, 0);
stream_set_blocking(STDIN, 0);

do {
  echo "$ ";
  $read   = array( $socket, STDIN); $write  = NULL; $except = NULL;

  if(!is_resource($socket)) return;
  $num_changed_streams = @stream_select($read, $write, $except, null);
  if(feof($socket)) return ;


  if($num_changed_streams  === 0) continue;
  if (false === $num_changed_streams) {
      /* Error handling */
    var_dump($read);
    echo "Continue\n";
    die;
  } elseif ($num_changed_streams > 0) {
    echo "\r";
    $data = fread($socket, 4096);
    if($data !== "") 
      echo "<<< $data";

    $data2 = fread(STDIN, 4096);

    if($data2 !== "") {
      echo ">>> $data2";
      fwrite($socket, trim($data2));
    }
  }

} while(true);