首页 > 解决方案 > 在 Python 中打开文件时出现 Apache 权限错误

问题描述

我是网页设计的新手,我正在尝试为一些 python 代码设置一个 Apache Web 界面。我正在运行一个测试 python 脚本,它只是在 /var/www/html/ 中打开一个名为 output.txt 的新文件并尝试写入它。加载网页后,我使用shell_exec('/usr/bin/python3 /var/www/html/ptest.py');运行我的 python 脚本。python 脚本确实运行并输出了一些打印消息,但尝试打开 output.txt 失败并显示: Traceback(最近一次调用最后一次):文件“/var/www/html/ptest.py”,第 8 行,在 f=open ("/var/www/html/output.txt", "w") PermissionError: [Errno 13] Permission denied: '/var/www/html/output.txt'。如果文件已经存在并且我打开阅读,它也会失败。

我已经确认该脚本是由 apache 运行的getpass.getuser(),并且我已经尝试了尽可能多的不同权限组合 /var/www/html/,包括 777。我已将 apache 设置为每个目录的组/var/ 到 html/。我已经尝试使用 777 权限提前创建文件。我已检查 /var/ 到 html/ 具有组执行权限。我尝试创建和使用另一个完全由 apache 拥有的文件夹。

我查看了 apache 指令,看看是否有我需要的指令,但我还没有找到。

我在下面包含了我的 python 脚本和我的 php 页面的代码。

编辑:我尝试使用 .ptest.py 作为 apache 运行su -s /bin/bash apache

ptest.py 以这种方式成功运行,因此问题似乎不是与 apache 用户/组关联的权限。

ptest.py

#!/usr/bin/python3
import sys
import getpass
import os
sys.stderr = sys.stdout
print(getpass.getuser())
print(os.getgid())
f = open("/var/www/html/output.txt", "w")
f.write("banana")
f.close()
print("I wrote banana, which is a berry")

香蕉.php

<html>
    <head></head>
    <body>
        <h2>Welcome to the Program Test</h2>
        <?php
            echo "Created Command", "<br>";
            $output = shell_exec('/usr/bin/python3 /var/www/html/ptest.py');
            echo "Executed Command", "<br>";
            echo $output, "<br>";
            echo "End of output", "<br>";
            $output = shell_exec('ls /var/www/html/');
            echo $output;
        ?>
    </body>
</html>

标签: pythonphpapachelampcentos8

解决方案


感谢 domino_pl发表评论。

它看起来像典型的 selinux 问题。试试 selinux setenforce 0 – domino_pl


推荐阅读