如何允许www-data用户使用nginx执行bash脚本

I an Ubuntu 16.04 machine running NGINX and PHP. I would like to enable the www-data user (via web browser) to be able to access a PHP page (php-test.php) that will execute either a bash script (script_test.sh) or execute Linux CLI commands using shell_exec or exec.

I have done the following.

Created my bash script file script_test.sh

#!/bin/bash

whoami
echo $USER
echo 'test'

exit

when I run this from CLI, using

./ script_test.sh

It does indeed work and I can see the info echoed out in the CLI.

I then pursued the goal of being able to allow the www-data user run this bash script through a PHP page running on this same machine from NGINX.

I created my php page (php_test.php) and it contains the following

<?php

    chdir('/path/to/my/files/');
    shell_exec('./script_test.sh');  // ATTEMPT RUN SCRIPT
    shell_exec('/path/to/my/files/script_test.sh');  // ATTEMPT RUN SCRIPT

    echo 'test 123';  // SIMPLE ECHO IN THE PHP PAGE
?>

I then ran the following to modify the sudoers file, giving www-data access to the bash script

sudo nano /etc/sudoers

to which I added the following line

www-data ALL=NOPASSWD: /path/to/my/files/script_test.sh

I then made sure the script was executable, for the sake of my testing, not worrying about security, I just set it to 777 with the following command

sudo chmod 777 script_test.sh

From there I opened a web browser and browsed to the localhost (NGINX) web server (php_test.php) and the only thing I see on the page is the 'test 123' that I echo from PHP... none of the bash script appears to have run at all. I tailed the NGINX error log and don't see any error at all.

Is there another log that could contain clues on this?

What else should I check here?

Can you try to use passthru instead of shell_exec, and see the output anything?

Also try this, and see if it shows on the log file:

if(file_exists('/path/to/my/files/script_test.sh')) { die('File not found!'); }
shell_exec("nohup /path/to/my/files/script_test.sh > /path/to/my/files/output.log &");

Also, are you running PHP with the www-data user (check your fpm pool)? Do you have any error on /var/log/syslog or /var/log/auth.log ? Have you restarted the server after changing the sudo permissions?

What does su - www-data -c "whoami" and su - www-data -s /bin/bash -c "whoami" outputs?

Does su - www-data -s /bin/bash -c "/path/to/my/files/script_test.sh" output something?