Python CGI
Installation:
sudo apt-get install apache2 sudo apt-get install python3
Enable CGI processing in apache:
sudo a2enmod cgi
Configure Apache2:
sudo nano /etc/apache2/conf-enabled/host-cgi.conf
ScriptAlias /cgi-bin/ /home/test/scripts/techsupp_analyzer/ <Directory /home/test/scripts/techsupp_analyzer> AllowOverride None Allow from all Require all granted Options +ExecCGI AddHandler cgi-script .py </Directory>
Create Script:
sudo nano /home/test/scripts/techsupp_analyzer/cgi.py
#!/usr/bin/python3
# -*- coding: UTF-8 -*-# enable debugging
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print()
print("Hello World!")
Change Permissions:
sudo chown -R test:www-data cgi-bin/ sudo chmod +x cgi-bin/cgi.bin
Testing:
http://10.140.196.7/cgi-bin/cgi.py
Get inputs form URL
Create a test CGI script in cgi-bin dir:
nano test.py
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Make it executable:
sudo chmod +x test.py
Testing:
http://10.140.196.7/cgi-bin/test.py?first_name=My&last_name=Admin
Get Inputs from Form
File Structure:
--|---index.py | |---test.py
In the same dir as above test.py, create Form Page:
nano index.py
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print'<form action = "/cgi-bin/test.py" method = "get">'
print'First Name: <input type = "text" name = "first_name"> <br />'
print'Last Name: <input type = "text" name = "last_name" />'
print'<input type = "submit" value = "Submit" />'
print"</form>"
print "</body>"
print "</html>"
Make it executable:
sudo chmod +x index.py
Testing
http://10.140.196.7/cgi-bin/index.py