簡體   English   中英

如何通過ssh在PHP中執行遠程命令?

[英]How can I execute remote commands in PHP via ssh?

我試圖通過ssh在php腳本中執行遠程命令,我希望將命令(stdout和stderr)的輸出流式傳輸到原始主機。

我知道在Perl和Ruby中這是可能的。 我在php中找不到任何這樣的例子。

碼:

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

但是當我像這個$php remote.php一樣執行它時,我收到一個錯誤:

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

通過ssh在PHP中執行遠程命令的最佳方法是什么?

如果由於繁文縟節而無法添加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;
    }
}

安裝PECL SSH2軟件包是PITA。 試試phpseclib,一個純PHP SSH實現 看一下這篇文章,看看為什么要不惜一切代價避免PECL SSH2擴展:

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

通過SSH密鑰管理身份驗證非常簡單:

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

PHP 5.5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM