I want to run a Python script from PHP (long story), but I get a PermissionError. Running the Python script directly from command line with the PHP user seems to work fine however.
The server is running as user 967(nginx)
, who is member of the group pygroup
.
Here are the permissions of the directory with the python file (/var/www/py
):
-rwxrwxr-x. 1 homeuser pygroup 119 Mar 22 15:18 test.py
-rw-rw-r--. 1 homeuser pygroup 2 Mar 22 15:24 x.txt
The following Python script test.py
opens a file for writing in the same directory:
#!/usr/bin/env python3
import sys
import os
print("UID:", os.getuid())
print("EUID:", os.geteuid())
with open(os.path.join(sys.path[0],"x.txt"), "w") as f:
pass
Running it with sudo -u nginx /var/www/py/test.py
works fine:
UID: 967
EUID: 967
However, if I try to execute it with the following PHP script from another directory:
<?php
echo "UID: " . posix_getuid() . "\n";
echo "EUID: " . posix_geteuid() . "\n";
echo "Name: " . posix_getpwuid(posix_getuid())['name'] . "\n\n";
echo "Running python:\n";
echo shell_exec("/var/www/py/test.py 2>&1");
Then I get the following output:
UID: 967
EUID: 967
Name: nginx
Running python:
UID: 967
EUID: 967
Traceback (most recent call last):
File "/var/www/py/test.py", line 8, in <module>
with open(os.path.join(sys.path[0],"x.txt"), "w") as f:
PermissionError: [Errno 13] Permission denied: '/var/www/py/x.txt'
That confirms that the PHP script is running as user nginx
. But it throws an error, while running it from command line as this user works fine.
SELinux is set to permissive. There are no errors in the Nginx and SELinux logs either. What could I have missed?
UPDATE 2021-03-23: It seems to work irregularily. Every 10 or so attempts the write works when calling the python script from PHP. What could be the issue?
Not only was the write permitted sporadically, also SELinux reported errors just sometimes.
Solution: Most package updates were installed, every troubleshoot suggestion of the SELinux logs was executed, and the machine was rebooted. Afterwards, I've had to set SELinux to permissive again.
That doesn't explain why the write only worked sometimes, but it does work always now.