问题描述
我有我的2个按钮树莓派一个PHP网页(或关闭)
ON按钮按钮重定向到On.php
OFF按钮重定向到Off.php
在/ usr / lib目录/ cgi-bin目录我有一个Python脚本,我想执行(script.py)
我完全可以从终端通过键入执行它
I have a PHP webpage on my raspberry pi with 2 buttons (on and off)The on button button redirects to On.phpThe off button redirects to Off.phpIn "/usr/lib/cgi-bin" I have a python script that I would like to execute (script.py)I can perfectly execute it from the terminal by typing
cd /usr/lib/cgi-bin
sudo python script.py
它的工作原理,如果我这样做从终端。
It works if I do it from the terminal.
问题是在我的的/ var / www的文件夹中的PHP文件(On.php)。
这是我写的:
The problem is the PHP file (On.php) in my "/var/www" folder.This is what I wrote:
<?php
exec('cd /usr/lib/cgi-bin');
exec('sudo python script.py');
?>
为什么脚本从终端执行,而不是从我的PHP?
Why is the script executing from the terminal, but not from my PHP?
推荐答案
您不能从PHP脚本使用sudo。 Apache是从用户(www数据generaly)运行,因此编辑这个文件:的/ etc / sudoers文件
You can't use sudo from a PHP script. Apache is running from an user (www-data generaly), so edit this file : /etc/sudoers
然后加入这一行:
www-data ALL=(ALL) NOPASSWD:ALL
护理!这将授权所有功能由一个PHP脚本调用,可以适应不断变化的ALL的脚本或Python命令。
Care ! this will authorize all functions to be called by a PHP script, you can adapt changing "ALL" by your script or Python command.
然后precise你的用户在你的exec命令:
Then precise your user in your exec command :
<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/script.py')
这篇关于从PHP执行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!