Wednesday, April 14, 2010

File Uploading, 100% Python

I was trying to mix Perl and Python to achieve file uploading anywhere. After digging into the details of the BaseHTTPServer, I managed to craft out a 100% Python implementation. Together with my downloading server, I am now able to transfer files with ease in my current 'restricted' environment.
#! /usr/bin/python


import BaseHTTPServer
import os, cgi, re, random, platform


class GetHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        message = '<title>Upload</title>\
            <form action=/ method=POST ENCTYPE=multipart/form-data>\
            <input type=file name=upfile> <input type=submit value=Upload>\
            </form></body></html>'
        self.send_response(200)
        self.end_headers()
        self.wfile.write(message)
        return

    def do_POST(self):
        form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, \
            environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], })
        upfile = form['upfile']

        # extract basename of input filename, remove non-alphanumeric characters
        if '\\' in upfile.filename:
            filename = upfile.filename.split('\\')[-1]
        else:
            filename = upfile.filename.split('/')[-1]
        filename = re.sub('[ \t]','-', filename)
        filename = re.sub('[^a-zA-Z0-9_.:-]','', filename)

        fp = open(filename, 'wb')
        while True:
            chunk = upfile.file.read(8192)
            if len(chunk) == 0:
                break
            else:
                fp.write(chunk)
        fp.close()
        self.send_response(200)
        self.end_headers()
        self.wfile.write('<html><head><title>Upload</title></head><body>\
            <h1>Successfully uploaded</h1><br>From: %s<br>To: %s</body></html>' % \
            (upfile.filename, os.sep.join([os.getcwd(), filename])) )



if __name__ == '__main__':
    try:
        port = random.randint(50000,60000)
        url = "http://%s:%d/" % (platform.node(), port)
        server = BaseHTTPServer.HTTPServer( ('', port), GetHandler )
        print "Ask user to visit this URL:\n\t%s" % url
        server.serve_forever()
    except KeyboardInterrupt:
        pass

Labels:

0 Comments:

Post a Comment

<< Home