用exec在树莓派上执行python程序


PHP execute python program with exec on raspberry pi

我正在运行一个apache服务器,php安装在我的树莓派2 B+上。在我的php文件中有代码

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

不起作用。但是,当我在本地机器上的目录中运行相同的命令时,它可以工作。我也可以像ls

一样运行
 echo exec("ls");

命令可以工作,但是运行python代码的命令不起作用。我该如何着手解决这个问题?这个python文件设置一个GPIO并将其设置为LOW。任何帮助将不胜感激!由于

sudo文件

 #
 # 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

很可能您的Apache服务器没有足够的权限来执行该命令。您可以做很多事情,将您的www-data组添加到"sudo列表"。在/etc/sudoers中可以访问。

如果Apache组没有完整的sudo功能,您的原始模型可能无法工作。一种解决方法可能是创建一个shell脚本,如下所示:

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

然后将PHP修改为:

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

你会想要添加一些沿着这一行到/etc/sudoers文件:

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

虽然,考虑到在sudo列表中添加web服务器并不是通常推荐的事情,如果你可以绕过它。