4

I building one PHP application where I create command line functionality for Linux debian Jessie. All works fne but I need to be able use some commands like root user.

Is there a way to use shell_exec() or similar command to access like root user via PHP?

Idea of this command line is to people who have access to that server can handle with it over internet from any place or device.

Here is image of console:

enter image description here

Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78

2 Answers2

4

Executing commands as root via PHP will leave yourself wide open to all sorts of malicious hackery.

Have a look at the "sudo" documentation.

You should be able to set up all the commands you need as "sudo"able scripts. It is much better to write specific scripts with limited functions than to expose the underlying priviledged command.

As in:

exec ('sudo getCurrentUser.sh')

First, you need to add the user that PHP is using to run (most of the time it is www-data) to the sudo group if it is not already assigned.

Then, in your php file:

use sudo -S, so you can pass the password via echo

$exec = "echo your_passwd | /usr/bin/sudo -S your command";
exec($exec,$out,$rcode);

if you have trouble with the paths - use

"bash -lc 'echo your_passwd | /usr/bin/sudo -S your command'"

so you get a new bash that acts like a login shell and has the paths set

Hyder B.
  • 10,900
  • 5
  • 51
  • 60
  • This is great! I know that will be wide open but that's point of this because this server is local company server for our web dev team and they all have access via SSH clients but with this AP i will setup some users to just use non root and our team leaders will use full controll of console. THANKS! – Ivijan Stefan Stipić Mar 29 '17 at 14:39
  • One thing what I forget to mention, noone is sudoer. We not setup `sudo` users and that command not work on server. Only admins use own `su` access. – Ivijan Stefan Stipić Mar 29 '17 at 14:41
4

Edit your sudoers file

sudo vi /etc/sudoers

Put this line

www-data ALL=(ALL) NOPASSWD: ALL

www-data is the php default user in linux ( replace if necessary )

Use

$output = shell_exec('sudo XXXX');