0

I need to launch a command with sudo rights out of a php file (user: www-data), explicitly as user www-data:

<?php
    $command = 'sudo -u www-data /usr/bin/python3 /var/www/html/script.py';
    shell_exec($command);
?>

to be able to use sudo for www-data I want to put the command in sudoers (sudo visudo), like:

www-data ALL=NOPASSWD: sudo -u www-data /usr/bin/python3 /var/www/html/script.py

or

www-data ALL=NOPASSWD: -u www-data /usr/bin/python3 /var/www/html/script.py

but the syntax is wrong (error message from visudo). The following is working with sudoers (correct syntax)

www-data ALL=NOPASSWD: /usr/bin/python3 /var/www/html/script.py

but doesn't work for my script (apache error in log file):

Sorry, user www-data is not allowed to execute '/usr/bin/python3 /var/www/html/script.py' as www-data on raspberrypi.

it seems it needs sudo -u www-data. How can I solve this?

Dominic
  • 440
  • 8
  • 22
  • 1
    its not python you need sudo for, it would be the script. so make the script executable then owned by www-data then it would be `www-data ALL=(ALL:ALL) NOPASSWD: /var/www/html/script.py` – Lawrence Cherone Nov 19 '21 at 19:28

1 Answers1

1

It makes no sense to use sudo to allow www-data to run commands as www-data, but you can easily do so:

www-data ALL=(www-data) NOPASSWD: /usr/bin/python3 /var/www/html/script.py

The problem with your approaches was that you tried to add the command sudo -u www-data .. to sudoers, which corresponds to double-sudo sudo sudo -u www-data ..

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Yes, thank you! Now it makes sense and it works perfectly. visudo = www-data ALL=(www-data) NOPASSWD: /usr/bin/python3 /var/www/html/script.py AND shell_exec() with 'sudo -u www-data /usr/bin/python3 /var/www/html/script.py' combined with the tipps from @Lawrence Cherone chown www-data script.py and chmod +x script.py. – Dominic Nov 19 '21 at 20:05