#!/usr/bin/env python3 # python standard library from os import path import sys import argparse import signal # user installed libraries from tornado import ioloop, web, httpserver # ============================================================================ # WebApplication - Tornado Web Server # ============================================================================ class WebRedirectApplication(web.Application): def __init__(self, target='https://localhost'): handlers = [ (r'/*', RootHandler), # redirect to https ] super().__init__(handlers) self.target = target # ============================================================================ # Handlers # ============================================================================ class RootHandler(web.RequestHandler): SUPPORTED_METHODS = ['GET'] def get(self): print('Redirecting...') self.redirect(self.application.target) # ------------------------------------------------------------------------- def signal_handler(signal, frame): r = input(' --> Stop webserver? (yes/no) ').lower() if r == 'yes': ioloop.IOLoop.current().stop() print('Webserver stopped.') sys.exit(0) # ------------------------------------------------------------------------- # Tornado web server # ---------------------------------------------------------------------------- def main(): # --- Commandline argument parsing argparser = argparse.ArgumentParser( description='Redirection server. Any request to http will be redirected to a target server provided in the command line argument.') argparser.add_argument('target', type=str, help='Target https server address, e.g. https://www.example.com.') argparser.add_argument('--port', type=int, default=8080, help='Port to which this server will listen to, e.g. 8080') arg = argparser.parse_args() # --- create web redirect application try: redirectapp = WebRedirectApplication(target=arg.target) except Exception as e: print('Failed to start web redirect application.') raise e # --- create webserver try: http_server = httpserver.HTTPServer(redirectapp) except Exception as e: print('Failed to create HTTP server.') raise e else: http_server.listen(8080) # --- run webserver print(f'Redirecting port {arg.port} to {arg.target} (Ctrl-C to stop)') signal.signal(signal.SIGINT, signal_handler) try: ioloop.IOLoop.current().start() # running... except Exception as e: print('Redirection stopped!') ioloop.IOLoop.current().stop() raise e # ---------------------------------------------------------------------------- if __name__ == "__main__": main()