#!/usr/bin/env python3 import argparse import sys import os.path import http.server import ssl def check_cert(dir): try: for i in 'cert', 'key': open(os.path.join(dir, 'https-%s.pem' % i)).close() except (FileNotFoundError, PermissionError) as e: print('Could not use %s: %s. Using http only.' % (dir, e.args[1])) return False except Exception as e: print('Error %d: %s' % e.args) sys.exit(e.errno) return True def main(address, port, tls_dir): use_tls = check_cert(tls_dir) port = 80 if port == 443 and not use_tls else port try: server = http.server.HTTPServer((address, port), http.server.SimpleHTTPRequestHandler) if use_tls: tls_socket = ssl.wrap_socket(server.socket, server_side=True, certfile=os.path.join(tls_dir, 'https-cert.pem'), keyfile=os.path.join(tls_dir,'https-key.pem'), ssl_version=ssl.PROTOCOL_TLSv1_2) server.socket = tls_socket except Exception as e: print('Error %d: %s' % e.args) sys.exit(e.errno) print('Serving on %s:%d...' % (address, port)) try: server.serve_forever() except KeyboardInterrupt: print(' Bye.') server.socket.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description="Hyperminimal https server") parser.add_argument('address', nargs='?', type=str, default='0.0.0.0', help='bind ip address (default: 0.0.0.0)') parser.add_argument('port', nargs='?', type=int, default=443, help='bind port number (default: 80 or 443)') parser.add_argument('-t', '--tls', type=str, default='/usr/local/etc/openssl', help='cert/key couple directory. Must be PEM \ formatted and named https-key.pem, https-cert.pem \ (default: /usr/local/etc/openssl)') args = parser.parse_args() main(args.address, args.port, args.tls)