PHP Run command as sudo without changing any Apache settings

Here is how to run a php script as sudo without changing apache settings.

Save the following snippet as This will act as the receiving script to run commands with sudo permissions.

while :; do
    command=$(nc -l 1234)
    # "[Sun Apr 21 14:46:34 PDT 2013] ":command""
    echo "["$(date)"] \"${command}\""
    # Run command received with sudo permissions
    sudo -i "${command}"
    echo -e "\nreturn code: ${?}"

Run this script with sudo and keep the script running:

$ sudo bash

Now send a command to be run. Here are two examples to issue commands:

Inside a php script

$data = 'whoami'; // Command to send
$fp = stream_socket_client('tcp://');
fwrite($fp, $data);

On the command line

$ echo "whoami" >/dev/tcp/localhost/1234

Example response:

$ sudo bash 
[Sun Apr 21 16:16:54 PDT 2013] "whoami"
return code: 0
If you liked this posting, please feel free to leave me a comment below.
View this page on GitHub.
Posted .


Leave a Reply