<?php

class SSH
{
  var $HostName;
  var $UserName;
  var $Password;
  var $Methods;

  function __construct($HostName = 'localhost', $UserName = 'admin', $Password = '')
  {
    $this->HostName = $HostName;
    $this->UserName = $UserName;
    $this->Password = $Password;
  }

  function Execute($Commands)
  {
    echo($Commands);
    if(!function_exists("ssh2_connect")) die("Function ssh2_connect doesn't exist");
    if(!($this->Session = ssh2_connect($this->HostName, 22, $this->Methods))) echo("Fail: Unable to establish connection to host\n");
    else
    {
      if(!ssh2_auth_password($this->Session, $this->UserName, $this->Password)) echo("Fail: unable to authenticate\n");
      else
      {
        //if(!($Stream = ssh2_shell($this->Session, 'xterm', null, 80, 40, SSH2_TERM_UNIT_CHARS))) echo("Fail: unable to execute command\n");
        if(!($Stream = ssh2_exec($this->Session, $Commands))) echo("Fail: unable to execute command\n");
        else
        {
          $Response = '';
          stream_set_blocking($Stream, true);
          while($Buffer = fread($Stream, 4000))
          {
            $Response .= $Buffer;
          }
            /*
            //echo(') '.strlen($Buffer).' '.ord($Buffer{0}).'(');
            for($I = 0; $I < strlen($Buffer); $I++) 
            {
              if(((ord($Buffer{$I}) >= 32) and (ord($Buffer{$I}) <= 128)) or ($Buffer{$I} = "\n") or ($Buffer{$I} = "\r")) echo($Buffer{$I});
              if($Buffer{$I} == '>')
              {
                fwrite($Stream, $Commands."\n\r");
                sleep(1);
              }
            }
            $Response .= $Buffer;
          }
          */
          fclose($Stream);
        }
      }
    }
    echo($Response);
    return(explode("\n", substr($Response, 0, -1)));
  } 
}
