【问题标题】:Executing shell script using php使用php执行shell脚本
【发布时间】:2013-02-10 05:26:59
【问题描述】:

我有一个 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 导入代码 远程:计数对象: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" 命令没有被执行并且它的输出没有显示出来。知道问题出在哪里吗?

【问题讨论】:

  • eval 有必要吗?你不能直接运行echo '0'; git pull -u origin master; echo '1'` 等
  • @Alison,在你说之后,我尝试删除 eval。直接调用它仍然运行,但通过php页面运行时结果相同。
  • 你试过在脚本顶部添加#!/bin/bash吗?

标签: php shell shell-exec


【解决方案1】:

这行得通

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

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

【讨论】:

    【解决方案2】:

    您可以使用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());
    ?>
    

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

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

    PHP 不仅适用于“网站”。即便如此,将管理脚本暴露给 Web 界面本身还是非常有用的。有时这甚至是项目要求。

    【讨论】:

      【解决方案3】:

      你应该尽量避免在 php 中运行 shell 命令。

      话虽如此,试试这个:

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

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

      【讨论】:

      • 更新了代码,此时尝试运行php脚本是否有错误提示?
      • @Sparky 道歉,尝试使用更新的功能 - 这个应该提供某种反馈。可能可能不会继续运行,但可能会让你更接近。 (我怀疑的问题是路径错误)
      【解决方案4】:

      这是正确的代码

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

      【讨论】:

      • 这没有回答问题。 (3 岁的)问题涉及一个特定的批处理作业,该作业已运行,但只是部分运行。这与ipconfig 无关。
      最近更新 更多