How to run PHP exec() as root?

2019-01-04 02:52发布

I'm trying to build a firewall manager in PHP, but when I execute, <?php exec('iptables -L'); ?>, the result array is empty.

I have tried, <?php echo exec('whoami'); ?>, and the response is www-data (the user that Apache is using). What can I do to execute the exec function as root? (Preferably without changing the Apache user.)

8条回答
Summer. ? 凉城
2楼-- · 2019-01-04 03:17

Just an assumption - Is this a PHP web app that will do this? This doesn't sound too safe. The app that needs root - could you build that separately and then invoke it from PHP? If not, maybe you can sudo the process so it can run as root.

查看更多
别忘想泡老子
3楼-- · 2019-01-04 03:24

I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS

After downloading you would simply use the following code:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1  = $shell->exeCmd('iptables -L');
//the return will be a string containing the return of the command
echo $return1;
查看更多
登录 后发表回答