Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call shell script from php that requires SUDO?

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?

like image 562
JD Isaacks Avatar asked Jul 02 '10 13:07

JD Isaacks


People also ask

How do I run a shell script in PHP?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix.

How do I run a shell script from the root?

To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user. Example: #!/usr/bin/sudo bash ....

Which operator is used to run the shell command in PHP?

The PHP execution operator consists of backticks (``) and is used to run shell commands. The output of the command will be returned, and may, therefore, be stored in a variable.


1 Answers

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 
like image 176
Brian Avatar answered Sep 30 '22 10:09

Brian