简体   繁体   中英

PHP execute python program with exec on raspberry pi

I am running an apache server with php installed on my raspberry pi 2 B+. In my php file I have the code

 echo exec("sudo chmod +x gpio.py && sudo python gpio.py 50");

which does not work. However, when I run this same command in the directory on the local machine, it works. I can also run like an ls

 echo exec("ls");

command and that works, but the command to run the python code doesn't work. How can I go about fixing this issue? This python file sets up a GPIO and sets it to LOW. Any help would be appreciated! Thanks

SUDOER FILE

 #
 # This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification
www-data ALL = NOPASSWD: /var/www/bash.sh
# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d
pi ALL=(ALL) NOPASSWD: ALL

Chances are your Apache Server does not have sufficient permissions to execute the command. You could do a number of things, adding your www-data group to the "sudo list". This is accessible in /etc/sudoers .

Your original model may not work if the Apache group does not have complete sudo capabilities. One workaround may be to create a shell script like the following:

#!/bin/bash
sudo chmod +x gpio.py && sudo python gpio.py 50 2>&1

Then change the PHP to the following:

echo exec("/path/to/my/script.sh");

You would want to add something along the lines of this to the /etc/sudoers file:

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

Although, take into account adding a web server to the sudo list is not something that's typically recommended, if you can get around it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM