Home >Backend Development >PHP Tutorial >How to Run Elevated Shell Scripts from PHP Using `sudo`?

How to Run Elevated Shell Scripts from PHP Using `sudo`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 17:13:031019browse

How to Run Elevated Shell Scripts from PHP Using `sudo`?

Executing Shell Scripts with Elevated Privileges in PHP

To execute a bash script that requires elevated privileges (via SUDO) from within PHP using shell_exec, there are two primary approaches:

Option 1: Disable Password Prompt

This method involves modifying the sudoers file (/etc/sudoers) by adding a rule that allows the web server user (e.g., www-data) to run the specified command without a password prompt. Open the sudoers file using the visudo command and add a line similar to the following:

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

This will allow the web server user to execute the script without being prompted for a password.

Option 2: Use PHP's proc_open

An alternative approach is to use the proc_open function in PHP. This function allows you to open a process and specify additional options, including providing the SUDO password as a parameter:

<?php
$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array("pipe", "w")   // stderr
);
$process = proc_open(
    "sudo /path/to/script",
    $descriptorspec,
    $pipes
);

// Write the password to stdin
fwrite($pipes[0], "your_sudo_password\n");
fclose($pipes[0]);

// Read stdout and stderr from pipes
while (!feof($pipes[1])) {
    $stdout .= fgets($pipes[1]);
}
while (!feof($pipes[2])) {
    $stderr .= fgets($pipes[2]);
}

proc_close($process);
?>

In this example, the SUDO password is provided as a string in the fwrite statement. Both methods effectively achieve the goal of executing the privileged script from PHP without being prompted for the password.

The above is the detailed content of How to Run Elevated Shell Scripts from PHP Using `sudo`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn