[英]Permission denied error when trying to make apache run Python through PHP in Linux
我需要一種通過 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)
所有文件都可以單獨正常工作。 通過互聯網瀏覽器訪問時,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 界面獲取參數,我很樂意使用它!
我自己解決了。 問題是由 SELinux 引起的。
首先,看看你的系統上是否有 SELinux:
sestatus
要暫時禁用它並查看這是否也是您的問題,請運行:
sudo setenforce 0
如果您的腳本在禁用它后仍然有效,請考慮放松 SELinux 或永久關閉它。 要永久關閉它,您可以點擊 此鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.