6

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.

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

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 like this $php remote.php, I get an error:

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?

2
  • 1
    It looks like you haven't install the pecl ssh2 package. Commented Jan 13, 2011 at 22:39
  • i did try to install SSH2, @ php.net/manual/en/ssh2.installation.php sudo pecl install ssh2 channel://pecl.php.net/ssh2-v Here is the stout: Failed to download pecl/ssh2 within preferred state "stable", latest release is version 0.11.2, stability "beta", use "channel://pecl.php.net/ssh2-0.11.2" to install parsePackageName(): "version" is neither a valid version nor a valid state in "channel://pecl.php.net/ssh2-version" invalid package name/package file "channel://pecl.php.net/ssh2-version" install failed and if i try from the source but could not figure out how to compile config.m4 Commented Jan 24, 2011 at 19:08

5 Answers 5

6

If you can't add php packages due to red tape, here's 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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You are saying he could add a php package, if this is not a red flag. What kind of PHP package your talking about? Some third party library? Any suggestions?
I think I was referring to the ssh2 pecl package. However since answering this almost 5 years ago, Composer has become a useful thing for php. Check out getcomposer.org for all the packages you could ever want.
2

Did you install the SSH2 package?

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

1 Comment

i tried, the install failed sudo pecl install ssh2 channel://pecl.php.net/ssh2-version [sudo] password for tester: Failed to download pecl/ssh2 within preferred state "stable", latest release is version 0.11.2, stability "beta", use "channel://pecl.php.net/ssh2-0.11.2" to install parsePackageName(): "version" is neither a valid version nor a valid state in "channel://pecl.php.net/ssh2-version" invalid package name/package file "channel://pecl.php.net/ssh2-version" install failed
2

Installing the PECL SSH2 package is a PITA. Try phpseclib, a pure PHP SSH implementation instead. Take a look at this post to see why the PECL SSH2 extension should be avoided at all costs:

www.frostjedi.com/phpbb/viewtopic.php?f=46&t=13223

Comments

2

With authentification managed by SSH keys it's quite simple :

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

PHP 5.5

Comments

1

at least on ubuntu: the following instructions work: http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ make_ssh_connections_with_php

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.