Can't get Python to work on LAMP Ubuntu

August 25, 2014 2.1k views

Hi,

I have a LAMP environment on Ubuntu and trying to get it to execute Python scripts. All of the files sit under /var/www/euromemes.com/public_html and all the scripts are in /var/www/euromemes.com/public_html/cgi-bin.

I started playing with this and basically I had access to all the files, but they were just displaying code, not executing. Example:
http://euromemes.com/cgi-bin/browser.py

After playing around I'm now not even able to access those files (404 on the files and 403 on cgi-bin). I reverted back to all previous changes, the only thing that is changed was me running "sudo a2enmod cgi".

[QUICK UPDATE: I can confirm that once I run sudo a2enmod cgi that gives me the 403 and 404 errors as described above. Without it running it simply displays the .py file code without executing it.]

I tried editing /etc/apache2/apache2.conf and currently it has this in there:

<Directory /> 
  Options FollowSymLinks 
  AllowOverride None 
  Require all denied 
</Directory>

<Directory /usr/share> 
  AllowOverride None 
  Require all granted 
</Directory>

<Directory /var/www/> 
  Options ExecCGI Indexes FollowSymLinks 
  AddHandler cgi-script .py 
  AllowOverride All 
  Require all granted 
</Directory>

This isn't getting the job done... Not sure why this is happening, I thought Options ExecCGI and AddHandler cgi-script .py would be enough. Also not entirely sure if I should be editing apache2.conf or whatever .conf files I have in etc/apache2/sites-available, possibly 000-default.conf? I would want all my sites (not just euromemes.com, but all in /var/www) to be able to handle Python scripts.

Thanks in advance!

Best,
Tom

1 Answer

First, are you seeing any error messages in your Apache logs?

tail /var/log/apache2/error.log

A couple common things to watch out for... Make sure the script is executable:

chmod +x /path/to/script.py

And that it is owned by the correct user (likely www-data):

chown -R www-data:www-data /var/www/

Here's a working mod_cgi configuration:

<IfModule mod_alias.c>
        <IfModule mod_cgi.c>
                Define ENABLE_USR_LIB_CGI_BIN
        </IfModule>

        <IfModule mod_cgid.c>
                Define ENABLE_USR_LIB_CGI_BIN
        </IfModule>

        <IfDefine ENABLE_USR_LIB_CGI_BIN>
                ScriptAlias /cgi-bin/ /var/www/cgi-bin/
                <Directory "/usr/lib/cgi-bin">
                        AllowOverride None
                        AddHandler cgi-script .py
                        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                        Require all granted
                </Directory>
        </IfDefine>
</IfModule>

This serves Python scripts from /var/www/cgi-bin/ at http://domain.com/cgi-bin/script.py

Have another answer? Share your knowledge.