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" sys.exit(1) # # ensure user own the directory, unless is root # uid=os.getuid() owner=os.stat('.') if uid==0 or uid==owner: port = random.randint(50000,60000) url = "http://%s:%d/" % (platform.node(), port) try: Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", port), Handler) print "Ask user to visit this URL:\n\t%s" % url httpd.serve_forever() except: pass else: print "ERROR. You have to be either root or owner of the directory" sys.exit(1)