CGI Programming with Python

CGI stands for common gateway interface, which is used to communicate between the backend program and the frontend. Mainly the CGI scripts are invoked by an HTML form.
Getting Started
We will use a Linux machine for the demonstration.
Let's install Apache httpd -
$ yum install httpd -y
After httpd is installed, start the httpd service by -
$ systemctl start httpd
Check whether the service has started or not by -
$ systemctl status httpd
You should get an output like this -

Now we have 2 directories as /var/www/html and /var/www/cgi-bin
Now let’s write our CGI script that will help us with remote execution.
Just go inside /var/www/cgi-bin directory and create this script with any name.
Explanation of the above script:
cgi is a Python module that will help us to implement cgi functionality.
More on the cgi module can be read here -
cgi.FieldStorage is used to collect the data, that is send in query from the HTML form after submit button is pressed.
getvalue gets the specific data from the query string.
Finally, subprocess is used to run the command on the server.
Make the script executable by -
$ chmod +x <script-name>.py
Disable selinux, though it is not recommended
$ setenforce 0
Do this if you want any command to run without any permission issues -
open the file /etc/sudoers and edit it like this -

Now create a HTML page with a simple form, inside /var/www/html directory
Now go to an http://<ip>/cgiwebpage.html on a browser you will see -

Now type a command and press Execute button.
For example, when we put cal command we get output as -

So now from our web browser we can execute any command or script on the server remotely.
We can also get the output directly by using the curl command -
$ curl http://<ip>/cgi-bin/cgicode.py?co=cal
0 at the starting is the status code, and 0 means the command run successfully.
My GitHub Profile -
My LinkedIn Profile -
https://www.linkedin.com/in/yash-indane-aa6534179/
Thank you 😎!
More content at plainenglish.io