Executing Root Commands through PHP
You have expressed a desire to execute commands with root privileges from your PHP code on your CentOS server. Let's explore the issue and present potential solutions.
The Issue:
You've attempted to use the exec() function to restart the sshd service, but it requires root access, which is not granted to the Apache user. While you've tried solutions such as running Apache with root privileges or modifying your sudoers file, they haven't resolved the issue.
Solution Using Binary Wrapper (With Suid Bit):
Set Ownership and Permissions: Ensure that the root user owns the script and that it has the following permissions:
Create a Binary Wrapper: Create a binary wrapper that will execute your shell script with root privileges. Here's an example wrapper:
# cat > wrapper.c <<CONTENT #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main (int argc, char *argv[]) { setuid (0); system ("/bin/sh /path/to/php_shell.sh"); return 0; } CONTENT
Compile and Set Permissions: Compile the binary wrapper and set it with the suid bit:
This php_root wrapper will execute the commands specified in php_shell.sh with root privileges when called.
Alternative Solution:
Instead of using an external shell script, you can embed the commands directly into the binary wrapper. Simply replace the content in step 3 with the commands you want executed with root privileges.
Caution:
It's essential to use absolute paths to the script you want executed to prevent malicious users from exploiting the binary to execute arbitrary commands.
The above is the detailed content of How to Execute Root Commands from PHP on CentOS?. For more information, please follow other related articles on the PHP Chinese website!