|
from __future__ import print_function |
|
from SimpleHTTPServer import SimpleHTTPRequestHandler |
|
import SocketServer |
|
import os |
|
import socket |
|
import sys |
|
|
|
""" |
|
Share a file over the local network. |
|
|
|
Usage: |
|
|
|
python sharefile.py <path-to-file> |
|
""" |
|
|
|
|
|
class HTTP404(Exception): |
|
pass |
|
|
|
|
|
class BaseHandler(SimpleHTTPRequestHandler, object): |
|
file_path = None |
|
|
|
def log_message(self, format, *args): |
|
pass |
|
|
|
def translate_path(self, path): |
|
translated = super(BaseHandler, self).translate_path(path) |
|
if translated != self.file_path: |
|
raise HTTP404() |
|
else: |
|
return self.file_path |
|
|
|
def do_HEAD(self): |
|
try: |
|
super(BaseHandler, self).do_HEAD() |
|
except HTTP404: |
|
self.send_error(404, "File not found") |
|
|
|
def do_GET(self): |
|
try: |
|
super(BaseHandler, self).do_GET() |
|
self.log_download() |
|
except HTTP404: |
|
self.send_error(404, "File not found") |
|
|
|
def log_download(self): |
|
print(" Downloaded from %s:%s" % self.client_address) |
|
|
|
|
|
def share(path): |
|
path = os.path.abspath(path) |
|
ip = socket.gethostbyname(socket.getfqdn()) |
|
base = os.path.basename(path) |
|
handler = type('Handler', (BaseHandler,), {'file_path': path}) |
|
httpd = SocketServer.TCPServer(("", 0), handler) |
|
port = httpd.socket.getsockname()[1] |
|
print("Download Link: http://%s:%s/%s" % (ip, port, base)) |
|
try: |
|
httpd.serve_forever() |
|
except KeyboardInterrupt: |
|
httpd.shutdown() |
|
|
|
|
|
def main(): |
|
if len(sys.argv) != 2: |
|
print("Usage: sharefile.py <path-to-file>", file=sys.stderr) |
|
share(sys.argv[1]) |
|
|
|
|
|
if __name__ == '__main__': |
|
main() |