How can I execute remote commands in PHP via ssh?

I am trying to execute remote commands from a php script on top of ssh, and I want the output from the commands (stdout and stderr) to be sent to the original host.

I know that in Perl and Ruby this is possible. I could not find such examples in php.

the 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) < $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;
      }
    }
  }
}

But when I execute it as $php remote.php, I get an error message:

PHP Fatal error:  Call to undefined function ssh2_connect() 
in /home/tester/PHP_SSH2/remote.php on line 6

What is the best way to execute remote commands in PHP via ssh?

+5
source share
5 answers

If you can't add php packages due to red tape, here is a simple class that can do the trick

class ExecuteRemote
{
    private static $host;
    private static $username;
    private static $password;
    private static $error;
    private static $output;

    public static function setup($host, $username=NULL, $password=NULL)
    {
        self::$host = $host;
        self::$username = $username;
        self::$password = $password;
    }

    public static function executeScriptSSH($script)
    {
        // Setup connection string
        $connectionString = self::$host;
        $connectionString = (empty(self::$username) ? $connectionString : self::$username.'@'.$connectionString);

        // Execute script
        $cmd = "ssh $connectionString $script 2>&1";
        self::$output['command'] = $cmd;
        exec($cmd, self::$output, self::$error);

        if (self::$error) {
            throw new Exception ("\nError sshing: ".print_r(self::$output, true));
        }

        return self::$output;
    }
}
+5
source

Have you installed the SSH2 package?

http://www.php.net/manual/en/ssh2.installation.php

+3
+3

, SSH-, :

$cmd = 'ssh user@host script ' . $arguments . ' 2>/dev/null';
$result = shell_exec($cmd);

PHP 5.5

+1

All Articles