Run CGI program on Raspberry Pi as WEB Server

Environment

  • Raspberry Pi 3B+
  • Raspbian GNU/Linux 9.4

Install Apache 2

$ sudo apt-get install apache2
$ sudo apache2 -v
Server version: Apache/2.4.25 (Raspbian)
Server built:   2018-03-31T08:47:16
$ ifconfig
inet x.x.x.x

Setup CGI

$ sudo a2enmod cgid
...
Module cgid already enabled
$ sudo systemctl restart apache2
$ sudo reboot
$ sudo mkdir /var/www/cgi-bin
$ sudo vim /etc/apache2/sites-enabled/000-default.conf
ServerName localhost
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
Options +ExecCGI
AddHandler cgi-script .cgi .pl .py .sh
$ sudo vim /etc/apache2/conf-available/serve-cgi-bin.conf
<IfDefine ENABLE_USR_LIB_CGI_BIN>
    ## old location and config
    #ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    #<Directory "/usr/lib/cgi-bin">
    # AllowOverride None
    # Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    # Require all granted
    #</Directory>

    ## new cgi-bin config and location
    ScriptAlias /cgi-bin/ /var/www/cgi-bin/
    <Directory "/var/www/cgi-bin/">
        AllowOverride None
        Options +ExecCGI
    </Directory>
</IfDefine> 
$ sudo systemctl restart apache2
$ sudo usermod -a -G gpio www-data
$ sudo adduser www-data gpio
The user `www-data' is already a member of `gpio'.
$ sudo usermod -a -G i2c www-data
$ sudo adduser www-data i2c
The user `www-data' is already a member of `i2c'.
$ sudo usermod -a -G video www-data
$ sudo adduser www-data video
The user `www-data' is already a member of `video'.
$ sudo reboot
$ sudo visudo
# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
www-data ALL=(ALL:ALL) ALL

Static CGI Test

$ cd ~/
$ vim cgitest.py
#!/usr/bin/python3
import cgi, cgitb
cgitb.enable()
print(“Content-type: text/html\n\n”)
print(”<html><head><title>Static CGI Test</title></head>”)
print(“<body><h1>Static HTML Test</h1></body>”)
print(“</html>”)
$ sudo cp ./cgitest.py /var/www/cgi-bin
$ sudo chmod 777 /var/www/cgi-bin/cgitest.py

Dynamic CGI Test

$ vim formtest.py
#!/usr/bin/python3
import cgi, cgitb
cgitb.enable()
print("Content-Type: text/html\n\n")
print("""
<html>
    <head>
        <title>Test CGI Form</title>
    </head>
    <body>
        <h1>Brian the robot</h1>
        <p>Enter a command.</p>
        <form method="post" action="formtest.py">
            <p>command: <input type="text" name="command"/></p>
        </form>
""")
form = cgi.FieldStorage()
if "command" in form:
    command = form["command"].value
    print("<p>You gave command: " + command + "</p>")

print("""
    </body>
</html>
""")
$ sudo cp ./formtest.py /var/www/cgi-bin
$ sudo chmod 777 /var/www/cgi-bin/formtest.py

Reference