使用php执行shell脚本

使用php执行shell脚本,php,shell,shell-exec,Php,Shell,Shell Exec,我有一个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 $output = shell_exec('./deploy.sh

我有一个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
$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";
0正在导入代码 远程:计数对象:5,完成。 远程:压缩对象:100%(2/2),完成。 远程:总计3(增量1),重复使用0(增量0) 拆包对象:100%(3/3),完成。 来自bitbucket.org:user/repo *分支主控->取头 正在更新db13xxx..6705xxx 1正在备份数据库中的现有数据。。 这是正确的。但是,我编写了一个PHP脚本,可以通过http调用deploy.sh脚本。本php页面内容如下:-

$output = `./deploy.sh`;
echo '<pre>', $output, '</pre>';
$output=`./deploy.sh`;
回显“”,$output“”;
当我通过浏览器调用此php文件时,实际上正在调用shell脚本,并且我得到以下输出:-

0 Importing the code
$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";
0正在导入代码 1正在备份数据库中的现有数据。。
问题是
eval“git pull-u origin master”
命令没有执行,其输出也没有显示。知道问题出在哪里吗?

您应该尽量避免在php中运行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());
?>
$output=shell_exec('./deploy.sh');
回显“$output.”;

根据:

使用
exec()
函数可以做的一件事是传递两个可选值以获得更多信息

下面是我用来测试web界面中的shell脚本的一些代码

<?php 
  $cmd = 'ifconfig'; // pass command here
  echo "<pre>".shell_exec($cmd)."</pre>";
?>

文件使用的是我在中使用的项目中的,但是您可以将字符串输出放在使用它的任何位置,或者
echo/print\r()
。还可以通过运行phpinfo()确保您未处于安全模式;很多人都有这个问题

此外,您没有理由避免在PHP中使用shell脚本。PHP是一种脚本语言,它在聚合许多shell脚本以允许更高级别的管理方面非常节省

PHP不仅仅适用于“网站”。即使如此,将管理脚本暴露于web界面本身也是非常有用的;有时候,这甚至是一个项目要求。

这很有效


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

这是正确的代码



是否需要
评估?您不能运行
echo“0”吗;git pull-u原始主机
;echo'1'等等@Alison,在你说了之后,我试着删除eval。它在直接调用时仍然运行,但在php页面中运行时的结果相同。您是否尝试过添加
#/bin/bash
到脚本顶部?更新了代码,当您尝试运行php脚本时是否出现错误消息?@Sparky抱歉,尝试使用更新的函数-此函数应该会给出某种反馈。可能不会继续跑,但可能会让你更靠近。(我怀疑问题是路径错误)这并不能回答问题。这个(3年前的)问题涉及一个特定的批处理作业,该批处理作业正在运行,但只是部分运行。它不是关于
ipconfig
<?php
$output = shell_exec('sh deploy.sh');
echo "$output";
?>
<?php 
  $cmd = 'ifconfig'; // pass command here
  echo "<pre>".shell_exec($cmd)."</pre>";
?>