简体   繁体   English

如何从 php 脚本执行 shell 命令

[英]How to execute a shell command from a php script

I would like to create a php script to execute a shell command and return its output.我想创建一个 php 脚本来执行 shell 命令并返回它的 output。 The server requires a private key.服务器需要私钥。 When I first decided to test this out I created this:当我第一次决定测试它时,我创建了这个:

<?php
$command = "ls";
$output = shell_exec($command);
echo "<pre>$output</pre>";
?>

That worked just fine.那工作得很好。 But when I changed $command to the command I really wanted to run:但是当我将$command更改为我真正想运行的命令时:

$command = "/etc/init.d/mycontrollerd status /etc/mycontrollerconfig";

it gave me this output:它给了我这个 output:

You need root privileges to run this script

My guess is I need to use sudo .我的猜测是我需要使用sudo Of course that will require putting the pem file somewhere on the server.当然,这需要将 pem 文件放在服务器上的某个位置。 Assuming I do that, what exactly should $command be?假设我这样做,那么$command究竟应该是什么? Should I use shell_exec() , exec() , system() or something else?我应该使用shell_exec()exec()system()还是其他什么?

It does not matter which php function you use to start the script - what lacks is the authorization of your user account.您使用哪个 php function 来启动脚本并不重要 - 缺少的是您的用户帐户的授权。

Either use sudo (preconfigure the web server user to run the exact command without password via visudo , and prefix the command with sudo ) or set up a setuid script that executes the command on itself.要么使用 sudo (预先配置 web 服务器用户通过visudo运行没有密码的确切命令,并在命令前加上sudo )或设置一个 setuid 脚本来自行执行命令。

What you really need to do is set your web server to run as a specific user (other than 'nobody' for example), or give that user permissions to what you want to execute.您真正需要做的是将您的 web 服务器设置为以特定用户身份运行(例如,“nobody”除外),或者授予该用户对您想要执行的权限的权限。

See also: PHP shell_exec() and sudo: must be setuid root另请参阅: PHP shell_exec() 和 sudo:必须是 setuid root

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM