首页 > 解决方案 > 尝试让 apache 在 Linux 中通过 PHP 运行 Python 时出现 Permission denied 错误

问题描述

我需要一种通过 web html 接口在我的 Linux 服务器上执行“python3.8 createfile.py”脚本的方法。将来我还需要它从 HTML Web 界面检索表单数据以作为参数提供给 shell 命令,因此该方法必须可扩展至此,但我现在不寻找这部分解决方案

我正在使用 PHP exec_shell 方法,但 Python 会引发错误:

[Errno 13] Permission denied: '/var/www/html/ytr/output/createfile_2020-10-16_203623.txt'

我在我的 CentOS linux VPS 上运行 apache (httpd)。

ytr/index.html

<! -- Version 0.10 -->
<form action="/ytr/testexec.php">
    <input type="submit" value="Open Script">
</form>

ytr/testexec.php

// version 0.10
<?php
$log = shell_exec("python3.8 /var/www/html/ytr/createfile.py");
echo "<pre>Erorr log: $log</pre>";
//header('Location: http://xxx.xxx.xxx.94/ytr/index.html?success=true');
//x's are of course real numbers.
?>

ytr/createfile.py

from datetime import datetime
import os
# version 0.10
# Maybe its going to be woring directory

scr_dir = os.path.dirname(os.path.realpath(__file__)) + "/output/"
fin_name = scr_dir + "createfile_" + \
    datetime.now().strftime("%Y-%m-%d_%H%M%S" + ".txt")

try:
    fin = open(fin_name, "w")
    fin.write("Today is " + str(datetime.now()))
except Exception as e:
    print(e)

所有文件单独工作正常。通过 Internet 浏览器访问时 index.html 可以正常显示;通过 linux CLI 调用时,testexec.php 成功运行 createfile.py,然后成功执行(在 ytr/output 中创建文件);在 Linux CLI 中手动调用“python3.8 createfile.py”也很有效。

当我单击页面上的“打开脚本”按钮时,文件没有出现在 ytr/output 中,我得到这个:错误显示在 Web 界面上

奇怪的是,PHP 脚本中没有包含在 $log 中的错误消息。

我尝试过的事情

先感谢您!

PS如果有另一个(非php)解决方案可以从html运行bash命令,并且将来能够从Web界面获取参数,我很乐意使用它!

标签: phphtmllinuxapacheshell

解决方案


我自己解决了。问题是由 SELinux 引起的。

首先,看看你的系统上是否有 SELinux:

sestatus

要暂时禁用它并查看这是否也是您的问题,请运行:

sudo setenforce 0

如果您的脚本在禁用后仍然有效,请考虑放松 SELinux 或永久关闭它。要永久关闭它,您可以点击此链接


推荐阅读