从 PHP 运行 Bash 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11052162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:40:07  来源:igfitidea点击:

Run Bash Command from PHP

phpbashexec

提问by r0skar

I have a bash script, that I run like this via the command line:

我有一个 bash 脚本,我通过命令行运行它:

./script.sh var1 var2

I am trying to execute the above command, after I call a certain php file.

在调用某个 php 文件后,我正在尝试执行上述命令。

What I have right now is:

我现在拥有的是:

$output = shell_exec("./script.sh var1 var2");
echo "<pre>$output</pre>";

But it doesn′t work. I tried it using execand systemtoo, but the script never got executed.

但它不起作用。我尝试过使用execsystem太,但剧本从来没有得到执行。

However when I try to run shell_exec("ls");it does work and $outputis a list of all files.

但是,当我尝试运行shell_exec("ls");它时,它确实有效并且$output是所有文件的列表。

I am not sure whether this is because of a limitation of the VPS I am using or if the problem is somewhere else?

我不确定这是因为我使用的 VPS 的限制还是问题出在其他地方?

回答by Robert K

You probably need to chdirto the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.

在调用脚本之前,您可能需要chdir到正确的目录。通过这种方式,您可以在调用 shell 命令之前确保脚本“位于”哪个目录中。

$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);

回答by Hrishikesh

Your shell_exec is executed by www-data user, from its directory. You can try

您的 shell_exec 由 www-data 用户从其目录执行。你可以试试

putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");

Where your script is located in /home/user/binLater on you can

你的脚本位于/home/user/bin以后你可以

$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;

To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh

显示命令的输出。(或者,在不导出路径的情况下,尝试提供脚本的完整路径,而不仅仅是 ./script.sh

回答by CommanderSpock

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

检查您使用的域的 php.ini 或 .htaccess 中是否没有设置 open_basedir。这会将您囚禁在您的域目录中,而 php 将只能在此目录中执行。