How to call shell script from php that requires SUDO?

Solution 1:

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

Solution 2:

There are various solutions for this problem.

  • First of all, consider changing the script permissions, if reason why you want sudo is simply a permission issue (see the comment I added to the question above).

  • Another approach would be using the setuid bit. [Edit: Looks like setuid does not work well with scripts. For explananations, see this link.]

  • A third, but very insecure method is to read the password from a password file. Warning: This is very insecure, if there's any other possibility, don't do it. And if you do it, try hiding the password file somewhere in your folder hierarchy.

    <?php
    shell_exec('sudo -u root -S bash script.sh < /home/[user]/passwordfile');
    ?>
    
  • And a fourth possibility is to use the NOPASSWD tag in the sudoers file. You should limit this power to the specific commands you need.

Solution 3:

You can add something like this to your sudoers file:

username ALL=NOPASSWD: /path/to/script

This will allow that particular user to call sudo on that particular script without being prompted for a password.