Skip to content

Instantly share code, notes, and snippets.

@hugsy
Created May 22, 2015 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugsy/c193ab229e6077b971f0 to your computer and use it in GitHub Desktop.
Save hugsy/c193ab229e6077b971f0 to your computer and use it in GitHub Desktop.
basic http server to use for quick upload and download
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
from urlparse import urlparse
from datetime import datetime
import os, sys, tempfile
__author__ = "@_hugsy_"
__version__ = 0.1
__desc__ = "basic http server to use for quick upload and download"
__file__ = "InAndOut.py"
HTTP_IP = "0.0.0.0"
HTTP_PORT = 1234
CRLF = "\r\n"
PATH = sys.argv[1] if len(sys.argv)>1 else "/tmp"
def build_header():
html = """<html>
<head><title>{0} in {1}</title>
<body>
<h1>{0} in '{1}'</h1><br>
""".format(__file__, PATH)
return html
def build_footer():
date = datetime.now().strftime("%c")
html = """
<br>
<i>Generated by {} at {}</i>
</body>
</html>
""".format(__file__, date)
return html
def build_upload_form():
data = """
<form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>"""
return data
def build_dirlist():
data = "<h2>Directory Listing</h2>"
for d in os.listdir(PATH):
dpath = os.path.join(PATH, d)
if os.path.isdir(dpath):
data += "[d] <i>%s/</i>" % dpath
data += "<br>"
for f in os.listdir(PATH):
fpath = os.path.join(PATH, f)
if os.path.isfile(fpath):
data += "[f] <i>%s</i>" % fpath
data += "<br>"
return data
class FakeHTTPdHandler (BaseHTTPRequestHandler):
__base = BaseHTTPRequestHandler
__base_handle = __base.handle
server_version = "%s/%f" % (__file__, __version__)
def handle(self):
(ip, port) = self.client_address
self.log_error("Incoming request from %s:%d" % (ip, port) )
self.__base_handle()
return
def recv(self, length):
return self.rfile.read(length)
def send(self, data):
return self.wfile.write(data)
def do_GET(self):
html = build_header()
path = ""
if "?uploaded=" in self.path:
path = self.path.split("?", 1)[1]
for arg in path.split("&"):
k,v = arg.split("=")
if k=="uploaded":
path = v
break
html += """<h3>File '%s' uploaded</h3>""" % path
html += build_upload_form()
html += "<br><hr><br>"
html += build_dirlist()
html += build_footer()
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", len(html))
self.end_headers()
self.send( html )
return
def do_POST(self):
l = int(self.headers["Content-Length"])
body = self.recv(l)
headers, file_content = body.split(CRLF*2, 1)
marker = "-"*20
i = file_content.find(marker)
if i==-1:
fpath = "failed"
else:
file_content = file_content[:i+len(marker)]
fd, fpath = tempfile.mkstemp(dir=PATH)
with os.fdopen(fd, 'wb') as f:
f.write( file_content )
self.send_response(302)
self.send_header("Location", "/?uploaded=%s" % fpath)
self.end_headers()
return
class FakeHTTPdServer(ThreadingMixIn, HTTPServer): pass
if __name__ == '__main__':
try:
print("Server loop running in %s on %s:%d" % (PATH, HTTP_IP, HTTP_PORT))
FakeHTTPdServer((HTTP_IP, HTTP_PORT),FakeHTTPdHandler).serve_forever()
except KeyboardInterrupt as ki:
print("Leaving...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment