[英]Executing shell script using php
我有一個shell腳本deploy.sh
,它包含以下內容: -
echo "0 Importing the code"
eval "git pull -u origin master"
echo "1 Backing up existing data in database.."
// -- other code follows here
當我使用終端直接執行腳本時,我得到以下輸出: -
0 Importing the code
remote: Counting objects: 5, done. remote: Compressing objects: 100% (2/2), done. remote: Total 3 (delta 1), reused 0 (delta 0) Unpacking objects: 100% (3/3), done. From bitbucket.org:user/repo * branch master -> FETCH_HEAD Updating db13xxx..6705xxx
1 Backing up existing data in database..
這是對的。 但是,我編寫了一個PHP腳本,我可以通過http來調用deploy.sh腳本。 這個php頁面的內容如下: -
$output = `./deploy.sh`;
echo '<pre>', $output, '</pre>';
當我通過瀏覽器調用這個php文件時,shell腳本實際上被調用了,我得到以下輸出: -
0 Importing the code 1 Backing up existing data in database..
問題是eval "git pull -u origin master"
命令沒有執行,它的輸出也沒有顯示。 知道問題是什么嗎?
這有效
<?php
$output = shell_exec('sh deploy.sh');
echo "$output";
?>
在此之前,請確保該文件具有chmod 777權限。
你應該盡量避免在php中運行shell命令。
話雖如此,試試這個:
$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";
使用exec()
函數可以做的一件事是傳遞兩個可選值以獲得更多洞察力。
這是我用來從Web界面測試shell腳本的一些代碼。
<?php
require_once(__DIR__.'/../libs/Render.php');
error_reporting(E_ALL);
//Initialize and Run Command, with a little trick to avoid certain issues
$target='cd ../../your/relative/path && ./CustomScript.sh';
$outbuf=exec($target,$stdoutbuf, $returnbuf);
//Structure
$htm= new renderable('html');
$html->children[]= $head= new renderable('head');
$html->children[]= $body= new renderable('body');
$body->children[]= $out= new renderable('div');
$body->children[]= $stdout= new renderable('div');
$body->children[]= $returnout= new renderable('div');
//Value
$out->content= 'OUTPUT: '.$outbuf;
$stdout->content= 'STDOUT: '.var_export($stdoutbuf,true);
$returnout->content= 'RETURN: '.$returnbuf; //127 == Pathing problem
//Output
print_r($html->render());
?>
File正在使用我在其中使用的項目中的可渲染類 ,但您可以將字符串輸出放在您使用它的任何位置或者echo/print_r()
。 還要確保運行phpinfo()時不處於安全模式; 很多人都有這個問題。
此外,沒有理由避免在PHP中使用shell腳本。 PHP是一種腳本語言,在聚合許多shell腳本以允許更高級別的管理方面非常節儉。
PHP不僅適用於'網站'。 即便如此,將管理腳本暴露給Web界面本身也是非常有用的; 偶爾這甚至是項目要求。
這是正確的代碼
<?php
$cmd = 'ifconfig'; // pass command here
echo "<pre>".shell_exec($cmd)."</pre>";
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.