Tuesday, August 25, 2009

Extending A Simple HTTP Server in Python

My users have this requirement of transferring files from a UNIX host to their desktop. Instead of asking them to install WinSCP or any other equivalent utility, I simply extend this Python simple http server so that they can launch the server whenever they want to transfer via browser. My modified script will listen to some random high port and also ensure that the user (unless you are root) has the ownership of the directory where they launch the http server. To avoid anyone run wild, it restricts user from launching it from the root "/" directory. This simple python script becomes pretty handy for ad-hoc file transfer.
#! /usr/local/bin/python
# minimal web server.  serves files relative to the current directory.
# random high port

import SimpleHTTPServer, SocketServer
import random, sys, os
import platform

# to avoid running wild
if os.path.realpath('.') == "/":
        print "ERROR. Cannot run under /. Run in another directory"

# ensure user own the directory, unless is root
if uid==0 or uid==owner:
        port = random.randint(50000,60000)
        url = "http://%s:%d/" % (platform.node(), port)
                Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
                httpd = SocketServer.TCPServer(("", port), Handler)
                print "Ask user to visit this URL:\n\t%s" % url
        print "ERROR. You have to be either root or owner of the directory"



Blogger Ivan Morgillo said...

Thank you!
I was looking for an easy way to run that server on a port different than 8000.
+1 kudos

1:52 AM  
Blogger chihungchan said...

Do you know that you can simple run this "python -m SimpleHTTPServer 1234" to listen at port 1234

10:14 PM  

Post a Comment

<< Home