title: How can I execute remote commands in PHP via ssh?
body: <p>I am trying to execute remote commands from within a php script over ssh, and I want the output from the commands (stdout and stderr) be streamed to the originating host.</p>
  
  <p>I know in Perl and Ruby this is possible.  I could not find any such examples in php.</p>
  
  <p>Code:</p>
  
  <pre><code>$ip = 'kssotest.yakabod.net';
  $user = 'tester';
  $pass = 'kmoon77';
  
  $connection = ssh2_connect($ip);
  ssh2_auth_password($connection,$user,$pass);
  $shell = ssh2_shell($connection,"bash");
  
  $cmd = "echo '[start]';your commands here;echo '[end]'";
  $output = user_exec($shell,$cmd);
  
  fclose($shell);
  
  function user_exec($shell,$cmd) {
    fwrite($shell,$cmd . "\n");
    $output = "";
    $start = false;
    $start_time = time();
    $max_time = 2; //time in seconds
    while(((time()-$start_time) &lt; $max_time)) {
      $line = fgets($shell);
      if(!strstr($line,$cmd)) {
        if(preg_match('/\[start\]/',$line)) {
          $start = true;
        }elseif(preg_match('/\[end\]/',$line)) {
          return $output;
        }elseif($start){
          $output[] = $line;
        }
      }
    }
  }
  </code></pre>
  
  <p>But when I execute it like this <code>$php remote.php</code>, I get an error:</p>
  
  <pre><code>PHP Fatal error:  Call to undefined function ssh2_connect() 
  in /home/tester/PHP_SSH2/remote.php on line 6
  </code></pre>
  
  <p>What is the best way to execute remote commands in PHP via ssh?</p>