2011-12-29 14 views
0

私が実行しようとしている簡単なスクリプトがあります。このスクリプトの目的は、別のネットワーク接続サーバ上でコマンドを実行することですssh 'hostname'コマンドと組み合わせてphpでexec()を使用するには?

<?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つの下の印刷行のいずれにも出力されません。ただし、上部にwhoamiexec()が期待どおりに印刷されます。だから私の質問は、最初のコマンドはなぜ機能し、2番目のコマンドは機能しないのでしょうか?

ネットワーク化された2台のサーバは内部ネットワーク上にあり、sshネットワークキーのペアリングで設定されています。コマンドはphp内からではなく、動作します。

ありがとうございました。

+0

これをどのユーザーで実行していますか?あなたがコマンドラインから 'sudo'を実行したときに動作しますか? –

+0

診断のためだけに: "#!/ bin/sh \ n ssh someotherhost ls -l/path/to/dir"をシェルスクリプトに入れて、 "print exec( ' whoami '); "、chmod 700それです。それから、コマンドラインからPHPを使ってexec()を使って試してみましょう –

答えて

1

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

個人的には、私はちょうどphpseclib, a pure PHP SSH implementationを使用します。

0

私は内部Web開発サーバー用のカスタムコントロールパネルを作成する方法を見つけなければなりませんでした。私はたくさんのことを見て、PHP用のSSHパッケージがあり、通常はsshその中に。あなたは、あなたのサーバーはそれを行うために、パスワードなしでターゲットに接続できるようにするために、サーバー上のキーを生成する必要があります:)

それを試してみたいことがあります

ssh-keygen -t rsa 
ssh-copy-id [email protected] 

検索に用ネット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のためのドキュメントでinterrestedされることがあります。http://ca3.php.net/manual/fr/book.ssh2.php

関連する問題