Sudo in PHP Exec()

How to call shell script from php that requires SUDO?

Edit the sudoers file (with visudo) and add a rule that allows the web server user to run the command without a password. For example:

www-data ALL=NOPASSWD: /path/to/script

how to run php exec with sudo on live server

I don't recommend running the script as sudo. A better alternative is to give permission to the web server (www-data user) to write to the ../../merchants directory.

First add yourself to the www-data group by running the command below.

usermod -a -G www-data <your-username>

Then give the ownership of the merchants folder to the www-data group using the command below.

chgrp www-data merchants

Lastly give the correct permissions to the merchants folder using the command below.

chmod g+rwxs merchants

Hope this helps you solve your issue.


EDIT

On CentOS, you should use apache instead of www-data.

Run PHP shell_exec() like root user

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



Related Topics



Leave a reply



Submit