2015-11-11 161 views
0

我嘗試ping www.google.deshell_exec並將結果存儲到一個變量中,但我從shell_exec得不到結果。sudo_exec什麼也沒有返回

<?php 
    $ping   = 'sudo ping -c 4 '; 
    $url   = 'www.google.de'; 

    $command  = $ping . $url; 

    $ping_result = shell_exec($command); 

    $datei   = fopen("/var/www/myProject/result_ping","w") or die ("Could not open file!"); 
    sleep(10); 

    if ($datei == false) 
    { 
     $ping_result = "Cannot open file!"; 
    } 
    else 
    { 
     fwrite ($datei , $ping_result); 
     fclose ($datei); 
    } 

    echo $command;  //Output:  sudo ping -c 4 www.google.de 
    echo $ping_result; //Output:  nothing 
?> 

文件result_ping擁有所有權利(chmod 777)。 也許網絡服務器不允許執行ping

回答

2

添加2>&1你的指揮,以確保你沒有得到那個了shell_exec會過濾掉的錯誤消息:

$command  = $ping . $url . ' 2>&1'; 

shell_exec將在出錯的情況下返回NULL。通過該修改,您可以將任何錯誤消息重定向到正常輸出,從而強制shell_exec顯示您通常會在控制檯會話中獲得的每條消息。

+0

非常感謝!現在我得到了:'sudo:沒有tty禮物,沒有askpass程序指定'輸出'ping_result'我會做我的研究。 – Black