php - 从 PHP 执行 Bash 脚本

标签 php linux bash

我正在从 PHP 调用 bash 脚本,但我遇到了一个奇怪的问题,只有传递给 bash 的特定参数值才能成功执行:

我的 PHP 代码很简单:

$result = shell_exec("/scripts/createUser.sh $uname");

Bash 脚本代码:

#!/bin/bash

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

usrname=$1
echo -e "Username: $1"

deploy="/wordpress.tar.gz"
dest="/data/$usrname"

mkdir -p $dest

cd $dest

tar zxvf $deploy -C $dest >/dev/null 2>&1

ls $dest

但是这个脚本只能成功mkdir,提取wordpress.tar.gz并列出文件夹当$uname == 'test'时,否则什么也不会发生(甚至不能mkdir)。

我将脚本chown给www用户并授予执行权限,没有帮助。并且已经尝试以 root 身份通过控制台运行这些命令,它们运行良好:

/scripts/createUser.sh admin
php deploy.php // in this script $uname == 'admin'

怎么会发生这种事?感谢您的想法!

最佳答案

我最近发布了一个项目,允许 PHP 获取真实的 Bash shell 并与之交互(如果需要,可以作为 root),它解决了 exec() 和 shell_exec() 的限制。在这里获取:https://github.com/merlinthemagic/MTS

下载后,您只需使用以下代码:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);
$return1  = $shell->exeCmd("/scripts/createUser.sh " . $uname);
//the return will be a string containing the return of the command
echo $return1;

但是由于您只是触发一堆 bash 命令,因此只需使用此项目逐个发出它们即可。这样您还可以处理异常并准确查看哪个命令返回意外的内容,即权限问题。

对于长时间运行的命令,您必须更改超时:

//is one hour enough?
$timeout = 3600000;
$return1  = $shell->exeCmd("/scripts/createUser.sh " . $uname, null, $timeout);

关于php - 从 PHP 执行 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31445659/

相关文章:

bash - bash :播放当前目录中的所有音频

PHP:管理实体类型的设计模式

php - 如何使用 WooCommerce 更改每行的产品类别数

linux - mxc_edid.c 支持 1920x720,嵌入式 Linux

bash - AWS上的Docker-环境变量未从主机继承到容器

bash - 列出名称中只有数字的文件

javascript - 日期 不专门在 laravel 中工作

php - 使用 mysql_fetch_array 时防止多次回显

linux - 将文件添加到 zip 文件中的特定目录

c++ - 按修改时间在c++中排序文件