Santosh42
Posts: 4
Joined: Thu May 18, 2017 5:58 am

Problem when trying to run python scripts from apache php

Mon May 22, 2017 10:46 am

Hey guys, when I use the command
sudo python3 /home/pi/Santosh/pyphp/on.py
from the rpi terminal it works fine... but the following code isn't able to execute the same command...

<?php
exec("sudo python3 /home/pi/Santosh/pyphp/off.py");
?>

I am running apache server on my rpi with this php code.

on.py:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
GPIO.output(12,True)

User avatar
topguy
Posts: 6288
Joined: Tue Oct 09, 2012 11:46 am
Location: Trondheim, Norway

Re: Problem when trying to run python scripts from apache ph

Mon May 22, 2017 2:27 pm

- Apache runs as user "www-data".
- www-data is not a user that have "sudo" access.

if you can add the user "www-data" to a group that has GPIO access then you should be able to just remove "sudo".

Santosh42
Posts: 4
Joined: Thu May 18, 2017 5:58 am

Re: Problem when trying to run python scripts from apache ph

Wed May 24, 2017 6:44 am

To my sudoers file I added

Code: Select all

www-data ALL=/home/pi/Santosh/pyphp/on.py NOPASSSWD
www-data ALL=/home/pi/Santosh/pyphp/off.py NOPASSWD
It wasn't working. Then I added

Code: Select all

www-data ALL=(ALL) NOPASSWD: ALL
Now its working.
Is this the best approach?

User avatar
topguy
Posts: 6288
Joined: Tue Oct 09, 2012 11:46 am
Location: Trondheim, Norway

Re: Problem when trying to run python scripts from apache ph

Wed May 24, 2017 9:21 am

Its not the most secure way, you have given a hacker the possibility to run commands as super-user, if they can hack the apache server.
It would be even worse if you started running apache2 as root ( not recommended at all ), but better if you could give the user www-data only access to the hardware/resources it really needs.

I don't know exactly why your first attempt failed, but getting that to work would be somewhat safer.
( there is an extra "S" in NOPASSWD on the first line btw. )

User avatar
mattrix
Posts: 133
Joined: Mon Mar 02, 2015 6:20 am
Location: Christchurch, New Zealand
Contact: Website

Re: Problem when trying to run python scripts from apache ph

Sat May 27, 2017 2:26 am

See my answer here:
viewtopic.php?f=32&t=111380&p=764439#p764439

Basically you make a Python API wrapper to do your GPIO functions.

This way, Apache doesn't need any extra permissions and remains secure.
www.matthuisman.nz

Return to “Python”