snippets

More or less useful code snippets
Log | Files | Refs

vshare.py (1899B)


      1 #!/usr/bin/python3
      2 
      3 # Script for quickly sharing a single file (working as a server) or
      4 # downloading a shared file (working as a client).
      5 # When working as a server, it serves the single file given as argument and
      6 # exits immediately after a single request has been made, i.e. when the file
      7 # has hopefully been downloaded once.
      8 # When acting as a client it downloads the file served by a vshare server
      9 # running at the given IP and port (another computer)
     10 
     11 import sys
     12 
     13 if len(sys.argv) < 3 or sys.argv[1] not in ['s', 'g']:
     14     print("Use:")
     15     print("  to serve:          " + sys.argv[0] + " s <filename>")
     16     print("  to get / download: " + sys.argv[0] + " g <server>")
     17     exit()
     18 
     19 # If arg is 'g', get file from the given server
     20 if sys.argv[1] == 'g':
     21     import requests
     22     url = sys.argv[2]
     23     if 'http' not in url[:4]:
     24         url = 'http://' + url
     25     res = requests.get(url)
     26     filename = res.headers['Filename']
     27     with open(filename, 'wb') as f:
     28         f.write(res.content)
     29     print("Got file '" + filename + "'")
     30     exit(1)
     31 
     32 
     33 # If arg is 's', share the given file
     34 from http.server import BaseHTTPRequestHandler, HTTPServer
     35 FILENAME=sys.argv[2]
     36 
     37 class StoppableServer(HTTPServer):
     38     def serve_forever(self):
     39         self.stop = False
     40         while not self.stop:
     41             self.handle_request()
     42 
     43 class OneShotServer(BaseHTTPRequestHandler):
     44 
     45     def do_GET(self):
     46         self.send_response(200)
     47         self.send_header('Content-type', 'application/octet-stream')
     48         self.send_header('Filename', FILENAME.split('/')[-1])
     49         self.end_headers()
     50         with open(FILENAME, 'rb') as f:
     51             self.wfile.write(f.read())
     52         print('File fetched. Closing server')
     53         self.server.stop = True
     54 
     55 
     56 vsrv = StoppableServer(('0.0.0.0', 8001), OneShotServer)
     57 print('Serving "' + FILENAME + '"')
     58 try:
     59     vsrv.serve_forever()
     60 except Exception:
     61     vsrv.shutdown()