从 PHP 执行 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31811253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute Python script from Php
提问by ChubbyChocolate
I have a PHP webpage on my raspberry pi with 2 buttons (on and off) The on button button redirects to On.php The off button redirects to Off.php In "/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
我的 raspberry pi 上有一个 PHP 网页,有 2 个按钮(开和关) on 按钮重定向到 On.php off 按钮重定向到 Off.php 在“/usr/lib/cgi-bin”中,我有一个 python 脚本我想执行 (script.py) 我可以通过键入从终端完美地执行它
cd /usr/lib/cgi-bin
sudo python script.py
It works if I do it from the terminal.
如果我从终端执行它,它会起作用。
The problem is the PHP file (On.php) in my "/var/www" folder. This is what I wrote:
问题是我的“/var/www”文件夹中的 PHP 文件 (On.php)。这是我写的:
<?php
exec('cd /usr/lib/cgi-bin');
exec('sudo python script.py');
?>
Why is the script executing from the terminal, but not from my PHP?
为什么脚本从终端执行,而不是从我的 PHP 执行?
采纳答案by Vincent Decaux
You can't use sudo from a PHP script. Apache is running from an user (www-data generaly), so edit this file : /etc/sudoers
您不能在 PHP 脚本中使用 sudo。Apache 正在从用户运行(通常是 www-data),因此请编辑此文件:/etc/sudoers
Then add this line :
然后添加这一行:
www-data ALL=(ALL) NOPASSWD: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.
小心!这将授权 PHP 脚本调用所有函数,您可以通过脚本或 Python 命令调整更改“ALL”。
Then precise your user in your exec command :
然后在您的 exec 命令中精确您的用户:
<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/script.py')
回答by Alberto Pagani
Try this out, it should be working:
试试这个,它应该可以工作:
<?php
system("cd /usr/lib/cgi-bin");
system("sudo python script.py");
?>
Or even this:
甚至这个:
<?php
system("cd /usr/lib/cgi-bin && sudo python script.py");
?>
回答by Code1
On an older Raspbian distribution you need to place your file in /var/www/file.py
. So in your file.php you add:
在较旧的 Raspbian 发行版上,您需要将文件放在/var/www/file.py
. 所以在你的 file.php 你添加:
{
exec("sudo python /var/www/file.py");
}
On a newer Raspbian Jessie you need to place your file in /var/www/html/file.py
, so in your file.php you need to add:
在较新的 Raspbian Jessie 上,您需要将文件放在/var/www/html/file.py
.php中,因此您需要在 file.php 中添加:
{
exec("sudo python /var/www/html/file.py");
}
Or just any file.py
或者只是任何文件.py
<?php
{
exec("sudo python test.py");
}
?>
?>
Note: For this to work you need to edit a file first to add these lines to allow passwordless sudo
注意:为此,您需要先编辑一个文件以添加这些行以允许无密码 sudo
sudo nano /etc/sudoers
sudo nano /etc/sudoers
then go to the bottom and add this
然后转到底部并添加此
pi ALL=(ALL) NOPASSWD: ALL<br>
www-data ALL=(ALL) NOPASSWD: ALL