0

我有一个要运行的简单脚本:

<?php
print exec('whoami');
$output2 = exec('ssh someotherhost ls -l /path/to/dir',$output);
print_r($output);
print_r($output2);
print $output2;
?>

此脚本的目标是在另一台联网服务器上运行命令。如果我从命令行运行上述ssh命令(用真实数据替换虚拟数据): ssh someotherhost ls -l /path/to/dir

它输出正确的 ls 行。但是,当我使用相同的命令从相同的目录运行上述脚本时,它不会在三个底部打印行中的任何一个中输出。但是,顶部的exec()with确实按预期打印出来。whoami所以我的问题是,为什么第一个命令有效而不是第二个?

请注意,两台联网服务器位于内部网络上,并使用 ssh 网络密钥对进行设置。该命令有效,只是不在 php.ini 中。

谢谢你的帮助。

4

2 回答 2

1

PHP 运行 ssh 命令的用户可能与您从 CLI 执行的用户不同。也许用户 PHP 正在运行它,因为它的密钥文件或其他东西中没有服务器密钥。

就个人而言,我只会使用phpseclib,一个纯 PHP SSH 实现

于 2011-12-30T21:48:38.233 回答
0

前段时间我不得不找到一种方法来为内部 Web 开发服务器制作一个自定义控制面板,我环顾四周,发现有一个用于 PHP 的 SSH 包,它通常带有 ssh。您可能想尝试一下:)

您必须在您的服务器上生成一个密钥,以允许您的服务器无需密码即可连接到目标,为此:

ssh-keygen -t rsa
ssh-copy-id root@targetmachine

在网上查找有关 RSA 密钥生成的更多信息,网上有很多信息。然后,只要做一个像这样的小函数,你就可以执行大量的命令了 :)

<?php

/**
 *
 * Runs several SSH2 commands on the devl server as root
 *
 */
function ssh2Run(array $commands){

        $connection = ssh2_connect('localhost');
        $hostkey = ssh2_fingerprint($connection);
        ssh2_auth_pubkey_file($connection, 'root', '/home/youruser/.ssh/id_rsa.pub', '/home/youruser/.ssh/id_rsa');

        $log = array();
        foreach($commands as $command){

                // Run a command that will probably write to stderr (unless you have a folder named /hom)
                $log[] = 'Sending command: '.$command;
                $log[] = '--------------------------------------------------------';
                $stream = ssh2_exec($connection, $command);
                $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

                // Enable blocking for both streams
                stream_set_blocking($errorStream, true);
                stream_set_blocking($stream, true);

                // Whichever of the two below commands is listed first will receive its appropriate output.  The second command receives nothing
                $log[] = 'Output of command:';
                $log[] = stream_get_contents($stream);
                $log[] = '--------------------------------------------------------';
                $error = stream_get_contents($errorStream);
                if(strlen($error) > 0){
                        $log[] = 'Error occured:';
                        $log[] = $error;
                        $log[] = '------------------------------------------------';
                }

                // Close the streams
                fclose($errorStream);
                fclose($stream);

        }

        //Return the log
        return $log;

}

此外,您可能会对 SSH2 for php 的文档感兴趣:http: //ca3.php.net/manual/fr/book.ssh2.php

于 2011-12-29T18:01:54.740 回答