Interview Questions

How to use Shell Commands for Web python

Python Questions and Answers

(Continued from previous question...)

How to use Shell Commands for Web python

It is possible to execute shell commands through CGI. The subprocess.Popen class is what is necessary. This module is new in python 2.4. os.popen4 can also be used if a hosting provider does not offer 2.4.

This handy script gets anything in its query string and execute it as a shell command:

print "Content-Type: text/plain"

# The subprocess module is new in 2.4
import os, urllib, subprocess as sub

# Retrieve the command from the query string
# and unencode the escaped %xx chars
str_command = urllib.unquote(os.environ['QUERY_STRING'])

p = sub.Popen(str_command,
# Change /bin/bash to the available or preferred shell
shell=True, stdout=sub.PIPE, stderr=sub.STDOUT)

std_out_err = p.stdout
print '$', str_command

Say you want to install Django in your site. Without this script you would have to download it to your local host, decompress it, and upload the uncompressed files by FTP.

With CGI you download it using curl or wget directly to a directory in your site's hierarchy like a tmp directory:

http://my_site.tld/ -o tmp/Django-0.95.tar.gz

The above is one only line. And the output in the browser:

$ curl -o tmp/Django-0.95.tar.gz

% Total   % Received % Xferd  Average Speed      Time       Curr.
                          Dload  Upload Total    Current  Left    Speed

 0 1257k    0  2479   0    0   7042    0  0:03:02  0:00:00  0:03:02  7042
 4 1257k    4 62727   0    0    98k    0  0:00:12  0:00:00  0:00:12  217k
32 1257k   32  404k   0    0   241k    0  0:00:05  0:00:01  0:00:03  303k
49 1257k   49  623k   0    0   235k    0  0:00:05  0:00:02  0:00:02  270k
78 1257k   78  983k   0    0   271k    0  0:00:04  0:00:03  0:00:01  299k
100 1257k  100 1257k  0    0   309k    0  0:00:04  0:00:04  0:00:00  338k

Four seconds to download 1,257k in my host provider. Now we untar it:

http://my_site.tld/ -xzvf tmp/Django-0.95.tar.gz

Depending on your host you will have to provide absolute directory paths.

Warning: If you ever use this sample code save it with another name and chmod it to 600 immediately after its use. Otherwise any one in the whole world will be able to execute whatever he wants in your host.

(Continued on next question...)

Other Interview Questions