简体   繁体   English

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

[英]PHP execute python program with exec on raspberry pi

I am running an apache server with php installed on my raspberry pi 2 B+.我正在运行一个 apache 服务器,我的 raspberry pi 2 B+ 上安装了 php。 In my php file I have the code在我的 php 文件中,我有代码

 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我也可以像 ls 一样跑

 echo exec("ls");

command and that works, but the command to run the python code doesn't work.命令并且可以,但是运行 python 代码的命令不起作用。 How can I go about fixing this issue?我该如何解决这个问题? This python file sets up a GPIO and sets it to LOW.这个python文件设置了一个GPIO并将其设置为低电平。 Any help would be appreciated!任何帮助,将不胜感激! Thanks谢谢

SUDOER FILE SUDOER文件

 #
 # 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.可能是您的 Apache 服务器没有足够的权限来执行该命令。 You could do a number of things, adding your www-data group to the "sudo list".您可以做很多事情,将您的www-data组添加到“sudo 列表”。 This is accessible in /etc/sudoers .这可以在/etc/sudoers访问。

Your original model may not work if the Apache group does not have complete sudo capabilities.如果 Apache 组没有完整的 sudo 功能,您的原始模型可能无法工作。 One workaround may be to create a shell script like the following:一种解决方法可能是创建一个如下所示的 shell 脚本:

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

Then change the PHP to the following:然后将PHP更改为以下内容:

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

You would want to add something along the lines of this to the /etc/sudoers file:您可能希望在/etc/sudoers文件中添加类似以下内容的内容:

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.虽然,考虑到将 Web 服务器添加到 sudo 列表并不是通常推荐的事情,如果你能绕过它的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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