问题描述
我的 raspberry pi 上有一个 PHP 网页,有 2 个按钮(打开和关闭)打开按钮按钮重定向到 On.php关闭按钮重定向到 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-data),因此请编辑此文件:/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 脚本调用所有函数,您可以通过脚本或 Python 命令修改ALL".
Care ! this will authorize all functions to be called by a PHP script, you can adapt changing "ALL" by your script or Python command.
然后在您的 exec 命令中精确您的用户:
Then precise your user in your exec command :
<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/script.py')
这篇关于从 PHP 执行 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!