brikas
brikas

Reputation: 341

Permission denied error when trying to make apache run Python through PHP in Linux

I need a way to execute "python3.8 createfile.py" script on my Linux server through a web html interace. In the future I will need it to also retrieve form data from HTML web interface to provide as arguments to the shell command, thus the method must be expandable to that, yet I am not looking for this part of the solution right now

I am using a PHP exec_shell method, but Python throws an error:

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

I am running apache (httpd) on my CentOS linux VPS.

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)

All of the files work properly alone. index.html is displayed properly when accessed through internet browser; when called through linux CLI, testexec.php successfully runs createfile.py, which then successfully executes (creating a file in ytr/output); manually calling "python3.8 createfile.py" in Linux CLI also works well.

When I click the "Open script" button on my page, the file does not appear in ytr/output and I get this: error displayed on web interface

Weirdly, there is no error message, that would be contained in $log in PHP script.

Things I have tried:

Thank you in advance!

P.S. If there is another (non php) solution that could run a bash command from html, with the ability to take parameters from web interface in the future, I would be happy to use it!

Upvotes: 2

Views: 1035

Answers (1)

brikas
brikas

Reputation: 341

I solved it myself. The problem was caused by SELinux.

First, see if you have SELinux on your system:

sestatus

To disable it temporarily and see if that is your problem too, run:

sudo setenforce 0

If your script worked after disabling it, consider relaxing SELinux or turning it off permanently. To turn it off permanently, you can follow this link.

Upvotes: 3

Related Questions