使用PHP执行Shell脚本

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 导入代码
remote: 计算对象数目:5,完成。
remote: 压缩对象:100%(2/2),完成。
remote: 共计 3(delta 1),复用 0(delta 0)
解压对象:100%(3/3),完成。
来自 bitbucket.org:user/repo
 * 分支            master     -> 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"命令没有被执行,而且它的输出也没有显示出来。你知道问题出在哪里吗?

eval 是必要的吗?你不能只运行 echo '0'; git pull -u origin master; echo '1'` 等命令吗? - Armand
@Alison,你说过后,我尝试移除了eval。它仍然可以直接调用运行,但是通过php页面运行时结果相同。 - Sparky
1
你尝试在脚本顶部添加 #!/bin/bash 了吗? - Armand
4个回答

4

这个有效

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

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


3
< p >使用 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());
?>

该文件使用了我所用项目中的可渲染类,但您可以将字符串输出放置在任何地方,就像echo/print_r()一样。同时,请确保您未开启安全模式,可通过运行phpinfo()方法来确认,许多人都会遇到这个问题。

此外,您没有理由不使用shell脚本来编写PHP代码。作为一种脚本语言,PHP非常善于聚合许多shell脚本以实现更高级别的管理。

PHP不仅仅是用于“网站”,即使是将管理脚本暴露给Web界面也相当有用;有时这甚至是项目需求之一。


3

代码已更新,您现在尝试运行 PHP 脚本时是否出现错误消息? - ChrisK
@Sparky 抱歉,请尝试使用更新的函数 - 这个应该会给出一些反馈。可能仍然无法运行,但可能会让你更接近解决问题。(我怀疑问题是路径错误) - ChrisK

-2
这是正确的代码。
<?php 
  $cmd = 'ifconfig'; // pass command here
  echo "<pre>".shell_exec($cmd)."</pre>";
?>

这并没有回答问题。这个(三年前的)问题涉及一个特定的批处理作业,它运行了,但只完成了部分。这与“ipconfig”无关。 - trincot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接