pythonphpapache

Allow python script to be executed by Apache, but not read in a browser


I have a website that uses a python script to get information from a separate entity. The python script is required due to the libraries in use and the structure of the other entity. The retrieved information will be used in various ways on the site.

The website itself is PHP running on Apache and there is a section that kicks off the python script. Obviously, being an Apache server, the python script is kicked off by Apache, so the script must be usable / readable by Apache.

The issue is that if a user goes to the location of the script (i.e. www.mysite.com/scripts/myscript.py), the code is viewable through the browser.

Is it possible to set up the permissions in such a way that Apache can continue to use the script, but when going to the script directly in a browser, the code cannot be viewed? I am also okay with changing the script to not be easily read (maybe obfuscate it?).

I have tried to change the .htaccess file to not allow the reading of files in that directory, but while it does direct to a 403 page when trying to view, it prevents the script from being used by Apache. I have also changed the permissions of the file to allow Apache to execute the file, but not read it... that seems to prevent Apache from reading the results from the script.

Any ideas?


Edit 1: I think it should be noted that the python script is being kicked off by PHP through the exec command: exec("$cmd > /dev/null 2>&1 & echo $!;"), where $cmd is the command to be executed. This may or may not be the best use case here. If there is another way to make PHP kick off a python script and get the results from the script, I am open to that alternative.


Solution

  • You're over-thinking it. Note how you're invoking the Python script:

    the python script is being kicked off by PHP through the exec command: exec("$cmd > /dev/null 2>&1 & echo $!;"), where $cmd is the command to be executed.

    What specifically is $cmd? The server can execute a script anywhere on the file system. It doesn't need to be in the Apache web root, and indeed has nothing to do with Apache.

    Simply put it somewhere else on the file system, outside of the website.