我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用BaseHTTPServer.HTTPServer()。
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()
def main(port=8000): thisdir = os.path.dirname(os.path.realpath(__file__)) rootdir = os.path.realpath(os.path.join(thisdir, os.pardir, os.pardir)) subdir = SubRepo.get_path() ctf = os.path.basename(rootdir) submissions = os.path.basename(Settings.submissions_project) routes = [ ('/%s' % ctf, rootdir), ('/%s' % submissions, subdir), ] forbidden = { LocalSettings.path(), TeamSecrets.path(), } HandlerClass = handler(routes, '/%s' % ctf, forbidden) server_address = ('localhost', port) httpd = HTTPServer(server_address, HandlerClass) sa = httpd.socket.getsockname() print("Serving HTTP on", sa[0], "port", sa[1], "...") httpd.serve_forever()
def serve_files (filename, maxdown = 1, ip_addr = '', port = 8080): global maxdownloads maxdownloads = maxdown # We have to somehow push the filename of the file to serve to the # class handling the requests. This is an evil way to do this... FileServHTTPRequestHandler.filename = filename try: httpd = BaseHTTPServer.HTTPServer ((ip_addr, port), FileServHTTPRequestHandler) except socket.error: print >>sys.stderr, "cannot bind to IP address '%s' port %d" % (ip_addr, port) sys.exit (1) if not ip_addr: ip_addr = find_ip () if ip_addr: print "Now serving on http://%s:%s/" % (ip_addr, httpd.server_port) while cpid != 0 and maxdownloads > 0: httpd.handle_request ()
def run_fake_ingest(metric_data): class FakeCollectdIngest(BaseHTTPRequestHandler): def do_POST(self): body = self.rfile.read(int(self.headers.getheader('Content-Length'))) metric_data.extend(json.loads(body)) self.send_response(200) self.send_header("Content-Type", "text/ascii") self.send_header("Content-Length", "2") self.end_headers() self.wfile.write("OK") print 'Starting ingest server on port 80' httpd = HTTPServer(('', 80), FakeCollectdIngest) httpd.serve_forever() print 'Ingest server shutting down' # Dumps all of the collected metrics back out as JSON upon request
def server_and_port(resources): """Return an unstarted HTTPS server and the port it will use.""" # Find a port, and bind to it. I can't get the OS to close the socket # promptly after we shut down the server, so we typically need to try # a couple ports after the first test case. Setting # TCPServer.allow_reuse_address = True seems to have nothing to do # with this behavior. worked = False for port in xrange(4443, 4543): try: server = HTTPServer(('localhost', port), partial(RequestHandler, resources)) except socket.error: pass else: worked = True server.socket = ssl.wrap_socket( server.socket, certfile=join(tests_dir(), 'certs', 'localhost', 'server.pem'), server_side=True) break if not worked: raise RuntimeError("Couldn't find an unused socket for the testing HTTPS server.") return server, port
def main(args): if len(args) < 3: print "Usage: testserver.py HOSTNAME TIMEOUT-PORT HTTP-PORT FILES-DIR" sys.exit(1) hostname = args[0] timeout_port = int(args[1]) http_port = int(args[2]) files_dir = args[3] timeoutd = TimeoutServer((hostname, timeout_port), TimeoutRequestHandler) t = threading.Thread(target=timeoutd.serve_forever) t.daemon = True t.start() base_url = "http://" + hostname + ":" + str(http_port) httpd = HTTPServer(base_url, files_dir, (hostname, http_port), HTTPRequestHandler) httpd.serve_forever()
def run(self): server = BaseHTTPServer.HTTPServer( ( self.args['lhost'], self.args['lport'] ), HTTPProxyRequestHandler ) log.warn(messages.module_net_proxy.proxy_set_address_s_i % ( self.args['lhost'], self.args['lport'] )) if self.args['no_background']: log.warn(messages.module_net_proxy.proxy_started_foreground) server.serve_forever() else: log.warn(messages.module_net_proxy.proxy_started_background) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start()
def get_request(self): print "Server(HTTPServer): Serving GET request..." global g_stopEvent """Get the request and client address from the socket.""" self.socket.settimeout(5.0) result = None while result is None: try: if g_stopEvent and g_stopEvent.isSet(): return None result = self.socket.accept() except socket.timeout: pass result[0].settimeout(1000) return result
def main(): logging.info('pyhttps {}'.format(version)) create_ssl_cert() atexit.register(exit_handler) if PY3: import http.server import socketserver import ssl logging.info('Server running... https://{}:{}'.format(server_host, server_port)) httpd = socketserver.TCPServer((server_host, server_port), http.server.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True) else: import BaseHTTPServer import SimpleHTTPServer import ssl logging.info('Server running... https://{}:{}'.format(server_host, server_port)) httpd = BaseHTTPServer.HTTPServer((server_host, server_port), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True) httpd.serve_forever()
def main(argv): import getopt, imp def usage(): print ('usage: %s [-h host] [-p port] [-n name] module.class' % argv[0]) return 100 try: (opts, args) = getopt.getopt(argv[1:], 'h:p:n:') except getopt.GetoptError: return usage() host = '' port = 8080 name = 'WebApp' for (k, v) in opts: if k == '-h': host = v elif k == '-p': port = int(v) elif k == '-n': name = v if not args: return usage() path = args.pop(0) module = imp.load_source('app', path) WebAppHandler.APP_CLASS = getattr(module, name) print ('Listening %s:%d...' % (host,port)) httpd = HTTPServer((host,port), WebAppHandler) httpd.serve_forever() return
def __init__(self, console, server_ip = '', server_port = 8003): #self.logger = logger global logger logger = console self.server_ip = server_ip self.server_port = server_port httpd = HTTPServer((self.server_ip, self.server_port), RestRequestHandler) logger.info('Started REST API Server on port ' + str(self.server_port)) global funcs funcs = ApiFunctions(logger) result = funcs.init() if result: httpd.serve_forever()
def run_action(self): current_cwd = os.getcwd() self.ui.print_msg("Starting web server on port %s" % self.vars["port"][0]) print "\033[33m" try: httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', int(self.vars["port"][0])), SimpleHTTPServer.SimpleHTTPRequestHandler) if self.vars["https"][0].lower() == "true": httpd.socket = ssl.wrap_socket(httpd.socket, certfile=self.vars["certificate"][0], server_side=True) os.chdir(self.vars["folder"][0]) httpd.serve_forever() except KeyboardInterrupt: print "\033[00m" self.ui.print_msg("Stopping web server") except: print "\033[00m" self.ui.print_error("The web server raised an exception") os.chdir(current_cwd)
def run(self): def on_ready_callback(parts): logger.debug( 'On ready called with parts %s, calling my callback', parts ) self.ready_callback(parts) logger.debug('Request finished') logger.debug( 'Starting http server on %s:%s' % (HTTP_ADDRESS, HTTP_PORT) ) try: self.server = HTTPServer( ( HTTP_ADDRESS, HTTP_PORT ), get_handler(on_ready_callback)) except OSError: logger.exception('Could not bind to address') self.started_event.set() else: self.started_event.set() logger.debug('Serving forever...') self.server.serve_forever() logger.debug('Server has shut down')
def main(): conf = EspConfig() try: server = HTTPServer((conf.SCRATCH_IP, conf.SCRATCH_PORT), makeScratchHandler(conf)) print "Listening httpserver on " + str(conf.SCRATCH_IP) + ":" + str(conf.SCRATCH_PORT) conf.espNetHandler = EspNetHandler(conf) conf.espNetHandler.start() server.serve_forever() except KeyboardInterrupt: print "\n^C received, shutting down the web server" if server is not None: server.socket.close() for device in conf.espHandlersByDevice.itervalues(): device.closeEsp()
def __init__(self, data): super(HttpServerThread, self).__init__() self.done = False self.hostname = 'localhost' class MockStardog(BaseHTTPServer.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() self.wfile.write(json.dumps(data)) self.http = BaseHTTPServer.HTTPServer((self.hostname, 0), MockStardog) self.port = self.http.server_port
def run(server_class=HTTPServer, handler_class=HandleHTTP, port=4443): hostname = '127.0.0.1' server_address = (hostname, port) httpd = server_class(server_address, handler_class) # TODO: Get https working with cert, no response atm when ssl wrapper is set # NOTE:Try and switch to SimpleHTTPRequestHandler #httpd.socket = ssl.wrap_socket (httpd.socket, certfile=PATH_TO_CERT, keyfile=PATH_TO_KEY, server_side=True) print() print 'Starting httpd...' try: # NOTE: 2nd httpd for reference #httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler) #httpd.socket = ssl.wrap_socket (httpd.socket, certfile='path/to/localhost.pem', server_side=True) httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() print time.asctime(time.localtime()), "Server Stops - %s:%s" % (hostname, port)
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)
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)
def main(): if len(sys.argv) != 2: print 'Usage: %s [port number (between 1024 and 65535)]' % sys.argv[0] sys.exit(0) try: port = int(sys.argv[1]) if port < 1024 or port > 65535: raise ValueError try: serv = HTTPServer(('', port), RequestHandler) ip = socket.gethostbyname(socket.gethostname()) print '[-] Web server is running at http://%s:%d/' % (ip, port) try: serv.serve_forever() except: print '[-] Exiting ...' except socket.error: print '[*] Error : a socket error has occurred' sys.exit(-1) except ValueError: print '[*] Error : an invalid port number was given' sys.exit(-1)
def main(): os.umask(002) # make directories group-writable port = 8000 remote_user = None opts, args = getopt.getopt(sys.argv[1:], 'ir:p:', ['interactive', 'remote-user=', 'port=']) assert not args for opt, val in opts: if opt in ('-i', '--interactive'): port = None elif opt in ('-r','--remote-user'): port = None # implies -i remote_user = val elif opt in ('-p', '--port'): port = int(val) if port: httpd = BaseHTTPServer.HTTPServer(('',port), RequestHandler) httpd.serve_forever() else: StdinoutHandler(remote_user)
def main(): # attempt to start server try: # change directory if necessary by adding call to os.chdir() #os.chdir('/usr/local/httpd/htdocs') # create server server = HTTPServer(('', 80), MyHandler) print 'Welcome to the machine... hit ^C once or twice to quit' print 'cwd:', getcwd() # enter server loop server.serve_forever() # quit requested except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close()
def run(server_class=HTTPServer, handler_class=S, port=8282): global httpd; try: server_address = ('', port) handler_class.allow_reuse_address = True httpd = server_class(server_address, handler_class) httpd.allow_reuse_address = True httpd.stopped = False print ('Starting httpd server . . .', port) httpd.serve_forever() except KeyboardInterrupt: httpd.stopped = True; httpd.shutdown() httpd.socket.close() httpd.server_close() print("\n\nclosed....\nSuccessfully!"); #except: # print "address already in use?"
def run(server_class=HTTPServer, handler_class=S, port=8282): global httpd; try: server_address = ('', port) handler_class.allow_reuse_address = True httpd = server_class(server_address, handler_class) httpd.allow_reuse_address = True print 'Starting httpd server . . .' httpd.serve_forever() except KeyboardInterrupt: httpd.server_close() print("\n\nclosed....\nSuccessfully!"); #except: # print "address already in use?"
def run_server(server_class=HTTPServer, handler_class=S, port=8003): global httpd; try: server_address = ('', port) handler_class.allow_reuse_address = True httpd = server_class(server_address, handler_class) httpd.allow_reuse_address = True httpd.stopped = False print ('Starting httpd server . . .', port) httpd.serve_forever() except KeyboardInterrupt: httpd.stopped = True; httpd.shutdown() httpd.socket.close() print("\n\nclosed....\nSuccessfully!"); #except: # print "address already in use?"
def run_server(server_class=HTTPServer, handler_class=S, port=8100): global httpd; try: server_address = ('', port) handler_class.allow_reuse_address = True httpd = server_class(server_address, handler_class) httpd.allow_reuse_address = True httpd.stopped = False print ('Starting httpd server . . .', port) httpd.serve_forever() except KeyboardInterrupt: httpd.stopped = True; httpd.shutdown() httpd.socket.close() print("\n\nclosed....\nSuccessfully!"); #except: # print "address already in use?"
def main(): global conf # load config try: with open(sys.argv[1]) as f: conf = yaml.load(f) except IOError as e: print(e) sys.exit(1) except (yaml.scanner.ScannerError, yaml.parser.ParserError, IndexError): print("ERROR: Cannot load config, YAML parser error") sys.exit(1) try: # start an http server server = HTTPServer(('', conf['pkgbot']['port']), RequestHandler) logger.info("Started {0} server on port {1}".format( __version__, conf['pkgbot']['port'] )) server.serve_forever() except KeyboardInterrupt: server.socket.close()
def run(server_class=HTTPServer, handler_class=simpleHTTPServer, port=80): hostname = "192.168.1.67" httpd = None try: server_address = (hostname, port) httpd = server_class(server_address, handler_class) quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' print 'Starting httpd server at http://%s:%s' % (hostname, port) print 'Server %s (bind-address): \'*\'; port: %s' % (hostname, port) print 'Quit the server with %s.' % quit_command print sys.version httpd.serve_forever() except (KeyboardInterrupt, SystemExit) as e: if e: print >> sys.stderr, e if httpd is not None: httpd.socket.close() print "Stopping httpd..." exit(0) finally: print "httpd stopped." sys.exit(0)
def __init__(self, computation, host='', port=8181, poll_sec=10, DocumentRoot=None, keyfile=None, certfile=None, show_task_args=True): self._lock = threading.Lock() if not DocumentRoot: DocumentRoot = os.path.join(os.path.dirname(__file__), 'data') self._nodes = {} self._updates = {} if poll_sec < 1: pycos.logger.warning('invalid poll_sec value %s; it must be at least 1', poll_sec) poll_sec = 1 self._poll_sec = poll_sec self._show_args = bool(show_task_args) self._server = BaseHTTPServer.HTTPServer((host, port), lambda *args: HTTPServer._HTTPRequestHandler(self, DocumentRoot, *args)) if certfile: self._server.socket = ssl.wrap_socket(self._server.socket, keyfile=keyfile, certfile=certfile, server_side=True) self._httpd_thread = threading.Thread(target=self._server.serve_forever) self._httpd_thread.daemon = True self._httpd_thread.start() self.computation = computation self.status_task = pycos.Task(self.status_proc) if computation.status_task: client_task = computation.status_task def chain_msgs(task=None): task.set_daemon() while 1: msg = yield task.receive() self.status_task.send(msg) client_task.send(msg) computation.status_task = pycos.Task(chain_msgs) else: computation.status_task = self.status_task pycos.logger.info('Started HTTP%s server at %s', 's' if certfile else '', str(self._server.socket.getsockname()))
def setUpClass(cls): """Create and serve a fake HTTP server.""" cls.httpd = HTTPServer(cls.server_address, cls.handler) cls.running_thread = threading.Thread(target=cls.httpd.serve_forever) cls.running_thread.start()
def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def test(HandlerClass = CGIHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): SimpleHTTPServer.test(HandlerClass, ServerClass)
def __init__(self, port, delay = None, handler_func = None): self.port = port RequestHandler.delay = delay RequestHandler.handler_func = [handler_func] RequestHandler.response_data = '{}' RequestHandler.response_code = 200 threading.Thread.__init__(self) self.server = HTTPServer(('localhost', self.port), RequestHandler)
def __init__(self, host='localhost', port=None, handler=LogginWebMonitorRequestHandler): if port is None: port = logging.handlers.DEFAULT_TCP_LOGGING_PORT + 1 BaseHTTPServer.HTTPServer.__init__(self, (host, port), handler) self.starttime = datetime.datetime.now()
def server_bind(self): BaseHTTPServer.HTTPServer.server_bind(self) self.socket.settimeout(1) self.run = True
def run(server_class=HTTPServer, handler_class=Server, port=80, username="", password=""): server_address = ('', int(port)) handler_class.username = username handler_class.password = password httpd = server_class(server_address, handler_class) # print 'Starting SmartSocks ...' print(green + '[SmarkSocks] Waiting for clients ...', reset) httpd.serve_forever()
def __init__(self, server_address, RequestHandlerClass, node_uuid): """Constructor overridden to provide ability to pass configuration arguments to the server""" secdir = secure_mount.mount() keyname = "%s/%s"%(secdir,config.get('cloud_node','rsa_keyname')) # read or generate the key depending on configuration if os.path.isfile(keyname): # read in private key logger.debug( "Using existing key in %s"%keyname) f = open(keyname,"r") rsa_key = crypto.rsa_import_privkey(f.read()) else: logger.debug("key not found, generating a new one") rsa_key = crypto.rsa_generate(2048) with open(keyname,"w") as f: f.write(crypto.rsa_export_privkey(rsa_key)) self.rsaprivatekey = rsa_key self.rsapublickey_exportable = crypto.rsa_export_pubkey(self.rsaprivatekey) #attempt to get a U value from the TPM NVRAM nvram_u = tpm_nvram.read_key_nvram() if nvram_u is not None: logger.info("Existing U loaded from TPM NVRAM") self.add_U(nvram_u) BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass) self.enc_keyname = config.get('cloud_node','enc_keyname') self.node_uuid = node_uuid
def __init__(self, server_address, db,RequestHandlerClass): """Constructor overridden to provide ability to read file""" self.db = db BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass)
def shutdown(self): BaseHTTPServer.HTTPServer.shutdown(self)
def __init__(self, server_address,db,RequestHandlerClass): """Constructor overridden to provide ability to read file""" self.db = db BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass)
def _start_server(self): if self._testMethodName in self.special_cases: self._special_case_handle() else: addr = (HOST, PORT) self.http_server = HTTPServer(addr, Handle) self.http_server.serve_forever()
def serve_metric_data(metric_data): class MetricDataSpewer(BaseHTTPRequestHandler): def do_GET(self): data = json.dumps(metric_data) self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.rfile.write(data) print 'Starting metric spewer on port 8080' httpd = HTTPServer(('', 8080), MetricDataSpewer) httpd.serve_forever() print 'Metric spewer shutting down'
def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) BaseHTTPServer.HTTPServer.server_bind(self)
def run(self): # Start hidden services if not self._hs.connect(self._config.server_password()): sys.exit(1) self._hs.set_own(self._config.challenge_port()) self._hs.bind(self._config.hidden_services()) # Setup paths data_dir = self._hs.get_data_dir() hostname_path = data_dir + "/hostname" signed_file = data_dir + "/HSVerifyd.asc" self._hs.close() if not os.path.isfile(signed_file): self._log.error("Signature file does not exists") exit(2) # Setup class ChallengeThread.gpg_keyid = self._config.gpg_keyid() ChallengeThread.signed_file_path = signed_file # Run auth server try: self._server = HTTPServer(('127.0.0.1', self._config.challenge_port()), ChallengeThread) # Wait forever for incoming htto requests self._server.serve_forever() except: self._log.error("There was an error when trying to bind the server") exit(2)
def AsServer(port=80, modules=None, docstyle=False, nsdict={}, typesmodule=None, rpc=False, addr=''): address = (addr, port) httpd = HTTPServer(address, SOAPRequestHandler) httpd.modules = modules httpd.docstyle = docstyle httpd.nsdict = nsdict httpd.typesmodule = typesmodule httpd.rpc = rpc httpd.serve_forever()
def cleanup(self): logger.debug("Cleaning up Magic Mirror platform") self.httpd.shutdown() self.shutdown = True # Subclass HTTPServer with additional callback