views:

85

answers:

3

I have a file that is a bash script that requires SUDO to work.

I can run it from the command line using SUDO but I will be prompted to put in the SUDO password.

I want to run this script from php via shell_exec but I if I call SUDO, its not like a command line where I can be prompted for the password. Is there a way to pass the password for sudo with the sudo call?

How can I do this?

+3  A: 

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
Brian
A: 

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.

Daniel Egeberg
This makes sense but one part confuses me... Where exactly do I put the line `username ALL=NOPASSWD: /path/to/script` What is my sudoers file?
John Isaacks
In `/etc/sudoers`, though you usually use the `visudo` command to edit that file.
Daniel Egeberg
+2  A: 

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.

danilo
Changing the script permission won't run it as root, and setuid doesn't work on scripts
Brian
No, it won't run it as root, but it would solve the issue if the reason for the sudo usage is simply the script not being executable.And about the setuid thing, looks like you're right. In that case, excuse my misinformation. I found an useful link about this topic: http://www.faqs.org/faqs/unix-faq/faq/part4/section-7.html
danilo