Welcome, guest | Sign In | My Account | Store | Cart

First of all, this code was written to take advantage of the custom CGI module that I wrote. The purpose for this script is to allow someone to view a CGI script through a server. I have the problem that when I click on a python (*.py) file while viewed through my browser, the script is run so that it cannot be viewed. Unless the script is using "cgi.execute(function, exception)", then there is no way of getting around the problem. Therefore, this CGI application was written so that python files (and only *.py files) can be viewed if the user knows either the filename of a file in the same directory as this script or the full path of a file somewhere on the host computer. WARNING: do not use this script if you do not want someone to view any and all python scripts on your computer!

Python, 35 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import cgi

def main():
    if cgi.dictionary is None or not cgi.dictionary.has_key('file'):
        show_form()
    else:
        show_file()

def show_form(error = ''):
    if error != '':
        error = '\t\t\t' + error + ' cannot be displayed.<br>\n'
    cgi.html('''<html>
\t<head>
\t\t<title>
\t\t\tPython Script Viewer
\t\t</title>
\t</head>
\t<body>
\t\t<form action="python_script_viewer.py">\n''' + error + '''\t\t\tPython Script Filename:<br>
\t\t\t<input type="text" name="file" size="50"><br>
\t\t\t<input type="submit" value="Display">
\t\t</form>
\t</body>
</html>''')

def show_file():
    try:
        if cgi.dictionary['file'][-3:].lower() != '.py':
            raise Exception
        cgi.plain(file(cgi.dictionary['file']).read())
    except:
        show_form(cgi.dictionary['file'])

if __name__ == '__main__':
    cgi.execute(main, 'python')

This program is very helpful is resolving said problem. However, please be aware of the warning.

2 comments

Stephen Chappell (author) 18 years, 6 months ago  # | flag

Found A Bug. Hadn't noticed a little error being displayed at the end of a file. Here is an improved show_file function.

def show_file():
    try:
        if cgi.dictionary['file'][-3:].lower() != '.py':
            raise Exception
        cgi.plain(file(cgi.dictionary['file']).read())
    except Exception, error:
        if str(error) != '0':
            show_form(cgi.dictionary['file'])
Stephen Chappell (author) 18 years, 6 months ago  # | flag

Better Correction. Here is the 2nd revision of the show_file() function. It is more precise in its purpose and now does exactly what it was supposed to do.

def show_file():
    try:
        if cgi.dictionary['file'][-3:].lower() != '.py':
            raise Exception
        cgi.plain(file(cgi.dictionary['file']).read())
    except Exception, error:
        if error.__class__ is not SystemExit:
            show_form(cgi.dictionary['file'])