如何通过 ssh 在 PHP 中执行远程命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4686091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:58:30  来源:igfitidea点击:

How can I execute remote commands in PHP via ssh?

phpssh

提问by kamal

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.

我正在尝试通过 ssh 从 php 脚本中执行远程命令,并且我希望命令(stdout 和 stderr)的输出流式传输到原始主机。

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

我知道在 Perl 和 Ruby 中这是可能的。我在 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 remote.php,我收到一个错误:

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?

通过 ssh 在 PHP 中执行远程命令的最佳方法是什么?

采纳答案by Parris Varney

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

如果由于繁文缛节而无法添加 php 包,这里有一个简单的类可以解决问题

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;
    }
}

回答by Jim W.

Did you install the SSH2 package?

您是否安装了 SSH2 软件包?

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

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

回答by calgaryhit

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

安装 PECL SSH2 包是一个 PITA。试试phpseclib,一个纯 PHP SSH 实现。看看这篇文章,看看为什么应该不惜一切代价避免使用 PECL SSH2 扩展:

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

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

回答by Fedir RYKHTIK

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

通过 SSH 密钥管理的身份验证非常简单:

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

PHP 5.5

PHP 5.5