Search This Blog

Saturday, November 10, 2018

How to execute Linux / UNIX commands from web page

In order to execute commands or shell script from a webpage you need:

CGI support with Apache web server with proper configuration.
For example, for default installation of Apache on Ubuntu, you need to enable CGI module. See here:

You need to store program in cgi-bin directory. If you are using Debian Linux default location for cgi-bin directory is /usr/lib/cgi-bin. Under Red Hat / Fedora it is /var/www/cgi-bin. Use text editor such as vi to create a first.cgi program:

$ cd /usr/lib/cgi-bin
$ vi first.cgi

first.cgi code listing:

echo "Content-type: text/html"
echo ""
echo "<!DOCTYPE html>"
echo "<html><head><title>Bash as CGI"
echo "</title></head><body>"
echo "<h1>Hello world lib</h1>"
echo "Today is $(date)"
echo "</body></html>"

Save and close the file. Setup execute permission on the script:

$ chmod +x first.cgi



You need to send headers, first three lines are almost same for all your script:

#!/bin/bash : First line tell Linux/UNIX how file first.cgi should be run. So it will use /bin/bash interpreter to execute your rest of program.
echo "Content-type: text/html" : Send html headers, you must include this line.
echo "" : Send a blank line, you must include this line.

Rest is html code. Take a close look at following echo command:

echo "Today is $(date)"

It use shell feature called command substitution. It allows the output of a command to replace the command name:


Your bash shell performs the expansion by executing command and replacing the command substitution. So date command get executed by replacing the its output.