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 行を出力します。ただし、同じコマンドを使用して同じディレクトリから上記のスクリプトを実行すると、下の 3 つの印刷行のいずれにも出力されません。ただし、上部のexec()withwhoamiは期待どおりに印刷されます。私の質問は、なぜ最初のコマンドが機能し、2 番目のコマンドが機能しないのですか?

ネットワーク化された 2 つのサーバーは内部ネットワーク上にあり、ssh ネットワーク キーのペアでセットアップされていることに注意してください。コマンドは機能しますが、php 内からではありません。

ご協力いただきありがとうございます。

4

2 に答える 2

1

PHPは、CLIから実行しているのとは異なるユーザーでsshコマンドを実行している可能性があります。キーファイルなどにサーバーキーがないため、ユーザーPHPが実行している可能性があります。

個人的には、純粋なPHPSSH実装であるphpseclibを使用します。

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

}

また、php 用の SSH2 のドキュメントに興味があるかもしれません: http://ca3.php.net/manual/fr/book.ssh2.php

于 2011-12-29T18:01:54.740 に答える