How to run Python script with correct permissions in PHP?

Question:

I can run below script to print lines from the file in PHP so it looks like PHP has appropriate permissions but I’m not entirely sure. I also tried to make script executable, but no change. Below script works from shell and it writes passed argument to file. What do I miss?

Python script:

#!/usr/bin/python3
import sys
ip = sys.argv[1]
with open('/var/www/public_html/images/.htaccess') as file:
    lines = file.readlines()
    print(lines)
    if not ip in file.read():
        lines = [line.rstrip() for line in lines]
        lines.insert(-1,'    Require ip '+ip)
        with open('/var/www/public_html/images/.htaccess','w') as f:
            for a in lines:
                f.write(a+'n')

PHP script:

  $ip = $_SERVER['REMOTE_ADDR'];
  $command = escapeshellcmd('/var/www/public_html/cgi-bin/test.py');
  $output = shell_exec($command).$ip;
  echo $output
Asked By: imperato

||

Answers:

pass the $ip argument inside the escapeshellcmd(). Also if you suffer from bad permission issues try to provide your python script as an input to python interpreter:

  $ip = $_SERVER['REMOTE_ADDR'];
  $command = escapeshellcmd('/usr/bin/python3 /var/www/public_html/cgi-bin/test.py '.$ip);
  $output = shell_exec($command);
  echo $output

Also, I don’t think your php script has enough access rights to patch .htaccess file. If so – it’s web server misconfiguration, so the idea of this script is very questionable.

Answered By: leo

maybe your server dont have the wsgi module
try to run on terminal:

a2enmod wsgi
Answered By: Ébano Assumpção
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.