3

我有一个deploy.sh包含以下内容的 shell 脚本:-

echo "0 Importing the code"
eval "git pull -u origin master"

echo "1 Backing up existing data in database.."
// -- other code follows here

当我直接使用终端执行脚本时,我得到以下输出:-

0 导入代码
远程:计数对象:5,完成。
远程:压缩对象:100% (2/2),完成。
远程:总计 3(增量 1),重用 0(增量 0)
拆包对象:100% (3/3),完成。
来自 bitbucket.org:user/repo
 * 分支主 -> FETCH_HEAD
更新 db13xxx..6705xxx
1 备份数据库中的现有数据..

这是对的。但是,我编写了一个 PHP 脚本,我可以使用它通过 http 调用 deploy.sh 脚本。这个php页面的内容如下:-

$output = `./deploy.sh`;
echo '<pre>', $output, '</pre>';

当我通过浏览器调用这个 php 文件时,shell 脚本实际上被调用了,我得到了以下输出:-

0 导入代码
1 备份数据库中的现有数据..

问题是该eval "git pull -u origin master"命令没有被执行并且它的输出没有显示出来。知道问题是什么吗?

4

4 回答 4

4

这有效

<?php
$output = shell_exec('sh deploy.sh');
echo "$output";
?>

在此之前确保该文件具有chmod 777权限。

于 2014-08-19T09:23:54.053 回答
3

您应该尽量避免在 php.ini 中运行 shell 命令。

话虽如此,试试这个:

$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";

根据:http ://www.php.net/manual/en/function.shell-exec.php

于 2013-02-25T05:32:04.590 回答
3

您可以使用该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 界面本身还是非常有用的。有时这甚至是项目要求。

于 2013-11-16T13:22:28.027 回答
-2

这是正确的代码

<?php 
  $cmd = 'ifconfig'; // pass command here
  echo "<pre>".shell_exec($cmd)."</pre>";
?>
于 2016-03-18T12:12:56.623 回答