2011-12-29 117 views
0

我有一個簡單的腳本我試圖運行:如何在php中將exec()與ssh'hostname'命令結合使用?

<?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行。但是,當我使用相同的命令從相同的目錄運行上述腳本時,它不會輸出到三條底部打印行中的任何一條。但是,頂部的與whoami按預期打印出來。所以我的問題是,爲什麼第一個命令工作,而不是第二個?

請注意,兩臺聯網服務器位於內部網絡上,並且使用ssh網絡密鑰對進行設置。該命令的作品,而不是從內部的PHP。

感謝您的幫助。

+0

你在用什麼用戶?當你從命令行以'sudo'作爲該用戶時,它是否工作? – 2011-12-29 17:51:23

+0

僅供診斷:請將「#!/ bin/sh \ n ssh someotherhost ls -l/path/to/dir」放入shell腳本中,並將其作爲「print exec(' whoami');「,chmod 700它。然後從命令行通過exec()從php中嘗試它 – 2011-12-29 18:00:09

回答

1

PHP可能使用不同的用戶運行ssh命令,而不是從CLI執行此命令。也許用戶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; 

} 

此外,你可能會在文檔被interrested爲SSH2的PHP噸:http://ca3.php.net/manual/fr/book.ssh2.php

相關問題