def run(self, config): HandlerClass = make_handler_class(config) httpd = HTTPServer( (str(config['listening_ip']), int(config['listening_port'])), HandlerClass) httpd.serve_forever()
content_len = int(self.headers.get('content-length', 0)) post_body = self.rfile.read(content_len) return self.do_GET(post_body) class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" pass if __name__ == '__main__': if os.environ.get('MULTITHREADING') == '1': server = ThreadedHTTPServer((QGIS_SERVER_HOST, QGIS_SERVER_PORT), Handler) else: server = HTTPServer((QGIS_SERVER_HOST, QGIS_SERVER_PORT), Handler) # HTTPS is enabled if any of PKI or OAuth2 are enabled too if HTTPS_ENABLED: if QGIS_SERVER_OAUTH2_AUTH: server.socket = ssl.wrap_socket( server.socket, certfile=QGIS_SERVER_OAUTH2_CERTIFICATE, ca_certs=QGIS_SERVER_OAUTH2_AUTHORITY, keyfile=QGIS_SERVER_OAUTH2_KEY, server_side=True, # cert_reqs=ssl.CERT_REQUIRED, # No certs for OAuth2 ssl_version=ssl.PROTOCOL_TLSv1) else: server.socket = ssl.wrap_socket( server.socket, certfile=QGIS_SERVER_PKI_CERTIFICATE,
sys.exit(1) # Should never get here. _mqtt_client = None # type: typing.Optional[mqtt.Client] _mqtt_topics = {} # type: typing.Dict[str, str] if _parsed_args.mqtt_host: _mqtt_topics['pub'] = os.path.join(_parsed_args.mqtt_topic, 'status') _mqtt_topics['sub'] = os.path.join(_parsed_args.mqtt_topic, 'command') _mqtt_client = mqtt.Client(client_id=_parsed_args.mqtt_client_id, clean_session=True) _mqtt_client.on_connect = mqtt_on_connect _mqtt_client.on_message = mqtt_on_message if _parsed_args.mqtt_user: _mqtt_client.username_pw_set(*_parsed_args.mqtt_user.split(':', 1)) _mqtt_client.connect(_parsed_args.mqtt_host, _parsed_args.mqtt_port) _mqtt_client.loop_start() _keep_alive = None # type: typing.Optional[KeepAliveThread] query_status = QueryStatusThread() query_status.start() _keep_alive = KeepAliveThread() _keep_alive.start() httpd = HTTPServer(('', _parsed_args.port), HTTPRequestHandler) try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close()
# Get user response = requests.get(f'https://api.{ENVIRONMENT}/api/v2/users/me', headers=request_headers) # Check response if response.status_code == 200: # Get JSON response body response_json = response.json() print('\n*** USER DATA ***') print(' id: ' + response_json['id']) print(' name: ' + response_json['name']) print(' email: ' + response_json['email']) else: print('Failure: ' + str(response.status_code) + ' - ' + response.reason) return response # >> END oauth-implicit-step-3 if __name__ == "__main__": webServer = HTTPServer((HOST_NAME, PORT), SampleServer) print(f"Server started http://{HOST_NAME}:{PORT}") webbrowser.open(f"http://{HOST_NAME}:{PORT}", new=2) try: webServer.serve_forever() except KeyboardInterrupt: pass webServer.server_close() print("Server stopped.") # >> END oauth-implicit
if sys.version_info < (3, 6): data = data.decode() self.send_response(200) self.send_header('content-type', 'text/html') self.end_headers() self.wfile.write(bytes('OK', 'utf-8')) events.handle_event(irc, event_type, json.loads(data)) return # Just run IRC connection event loop def worker(): irc.loop() irc = IrcConnection(server=config.IRC_SERVER, channel=config.IRC_CHANNEL, \ nick=config.IRC_NICK, passw=config.IRC_PASS, port=config.IRC_PORT) t = threading.Thread(target=worker) t.start() # Run Github webhook handling server try: server = HTTPServer((config.SERVER_HOST, config.SERVER_PORT), MyHandler) server.serve_forever() except KeyboardInterrupt: print("Exiting") server.socket.close() irc.stop_loop()
# json.dumps converti le dictionnaire python en JSON self.wfile.write(bytes(json.dumps(self.data), "utf-8")) # POST is for submitting data. def do_POST(self): content_length = int(self.headers['Content-Length']) # <--- Gets the size of data post_data = self.rfile.read(content_length) # <--- Gets the data itself print("Le serveur a reçu un POST!", self.path, post_data) # on lit le JSON et on ajoute l'objet au tableau des personnages (data) # notez qu'une fois le serveur tué, les modifications dans data seront perdues! new_characters = json.loads(post_data.decode('utf8')) self.data["personnages"].append(new_characters) self.send_response(201) self._set_headers() self.wfile.write(bytes(json.dumps(self.data), "utf-8")) myServer = HTTPServer((hostName, hostPort), MyServer) print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort)) try: myServer.serve_forever() except KeyboardInterrupt: pass myServer.server_close() print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort))
def run(port): httpd = HTTPServer(('localhost', port), HandlerHTTP) print("Démarage du serveur HTTP sur le port {0} (http://localhost:{1})". format(port, port)) httpd.serve_forever()
#!/usr/bin/env python3 # https://stackoverflow.com/a/47084250/2131094 import os import sys from http.server import HTTPServer, BaseHTTPRequestHandler port = os.environ.get("PORT", None) url = os.environ.get("REDIRECT_URL", None) class Redirect(BaseHTTPRequestHandler): def do_GET(self): self.send_response(302) self.send_header('Location', url + self.path[1:]) self.end_headers() print("Starting redirector HTTPServer.") print("Server params:", url, port) if not (url and port): print("PORT or REDIRECT_URL not set!") sys.exit(1) else: HTTPServer(("127.0.0.1", int(port)), Redirect).serve_forever()
def start(host, port, ike_port, enable_ssl, cert, verbose, hpfserver, hpfport, hpfident, hpfsecret, hpfchannel, serverid): """ A low interaction honeypot for the Cisco ASA component capable of detecting CVE-2018-0101, a DoS and remote code execution vulnerability """ hpfl = hpflogger(hpfserver, hpfport, hpfident, hpfsecret, hpfchannel, serverid, verbose) def alert(cls, host, port, payloads): logger.critical({ 'src': host, 'spt': port, 'data': payloads, }) #log to hpfeeds hpfl.log("critical", { 'src': host, 'spt': port, 'data': payloads, }) if verbose: logger.setLevel(logging.DEBUG) requestHandler = WebLogicHandler requestHandler.alert_function = alert requestHandler.logger = logger requestHandler.hpfl = hpfl def log_date_time_string(): """Return the current time formatted for logging.""" now = time.time() year, month, day, hh, mm, ss, x, y, z = time.localtime(now) s = "%02d/%3s/%04d %02d:%02d:%02d" % ( day, requestHandler.monthname[month], year, hh, mm, ss) return s def ike(): ike_server.start(host, ike_port, alert, logger, hpfl) t = threading.Thread(target=ike) t.daemon = True t.start() httpd = HTTPServer((host, port), requestHandler) if enable_ssl: import ssl if not cert: import gencert cert = gencert.gencert() httpd.socket = ssl.wrap_socket(httpd.socket, certfile=cert, server_side=True) logger.info( 'Starting server on port {:d}/tcp, use <Ctrl-C> to stop'.format( port)) hpfl.log( 'info', 'Starting server on port {:d}/tcp, use <Ctrl-C> to stop'.format( port)) try: httpd.serve_forever() except KeyboardInterrupt: pass logger.info('Stopping server.') hpfl.log('info', 'Stopping server.') httpd.server_close()
def serve_presentation(args): # Check whether the file or folder as input exists. if not os.path.exists(os.path.abspath(args.presentation)): print(f"File or folder '{args.presentation}' does not exists.") exit(-1) # XXX Bit of a hack, clean this up, I check for this twice, also in the template. if args.template and args.template not in ("simple", "default"): args.template = os.path.abspath(args.template) if args.targetdir: # Generate the presentation generate(args) else: # Server mode. Start a server that serves a temporary directory. with TemporaryDirectory() as targetdir: args.targetdir = targetdir args.presentation = os.path.abspath(args.presentation) # Set up watchdog to regenerate presentation if saved. event = threading.Event() event.set() thread = threading.Thread(target=generate_and_observe, args=(args, event)) try: # Serve presentation if ":" in args.port: bind, port = args.port.split(":") else: bind, port = "0.0.0.0", args.port port = int(port) # First create the server. This checks that we can connect to # the port we want to. os.chdir(targetdir) server = HTTPServer((bind, port), SimpleHTTPRequestHandler) print("Serving HTTP on", bind, "port", port, "...") try: # Now generate the presentation thread.start() try: # All is good, start the server server.serve_forever() except KeyboardInterrupt: print("\nKeyboard interrupt received, exiting.") finally: # Server exited server.server_close() finally: # Stop the generation thread event.clear() # Wait for it to end thread.join() except PermissionError: print("Can't bind to port %s:%s: No permission" % (bind, port)) except OSError as e: if e.errno == 98: print("Can't bind to port %s:%s: port already in use" % (bind, port)) else: raise
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import Server from Server import MyServer from http.server import BaseHTTPRequestHandler, HTTPServer hostName = 'localhost' serverPort = 8888 if __name__ == "__main__": webServer = HTTPServer((hostName, serverPort), MyServer) print("Server started http://%s:%s" % (hostName, serverPort)) try: webServer.serve_forever() except KeyboardInterrupt: pass webServer.server_close() print("Server stopped.")
self._handle_all() def do_POST(self): self._handle_all() def do_PUT(self): self._handle_all() def do_HEAD(self): self._handle_all() if os.environ.get("DEBUG_CONTAINER", "false").lower() == "true": logging.warning(Maintenance.MESSAGE) port = int(os.environ.get("PORT", 8080)) httpd = HTTPServer(("", port), Maintenance) httpd.serve_forever() def emit(**stats): stats["version"] = "1.0" stats["timestamp"] = datetime.datetime.now().isoformat() logging.info("MENDIX-METRICS: %s", json.dumps(stats)) if __name__ == "__main__": app_is_restarting = False m2ee = None nginx_process = None logging.basicConfig(
import time from http.server import HTTPServer from server import Server # define two constants we’ll be using when we launch the server HOST_NAME = 'localhost' PORT_NUMBER = 8888 if __name__ == '__main__': # create the HTTP object with previous defined parameters httpd = HTTPServer((HOST_NAME, PORT_NUMBER), Server) print(time.asctime(), 'Server UP - %s:%s' % (HOST_NAME, PORT_NUMBER)) # this block actually starts up the server and runs it: try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() print(time.asctime(), 'Server DOWN - %s:%s' % (HOST_NAME, PORT_NUMBER))
fpem = default_fpem_path if not os.path.isfile(fpem): printc( "<red>The SSL certificate<white> file <black>{}<white> is not present, trying to generate it with a 'openssl' command ..." .format(fpem)) generate_certificate(fpem) printc( "<green>Using the SSL certificate<white> from the information in the file <black>{}<white> ..." .format(fpem)) # Serve render/ folder, not current folder os.chdir(os.path.join("..", "render")) try: httpd = HTTPServer((IP, PORT), CustomHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile=fpem, server_side=True) sa = httpd.socket.getsockname() IP, PORT = sa[0], sa[1] printc( "<green>Serving uLogMe<white> on a HTTPS server, see it locally on '<u><black>https://{}:{}<white><U>' ..." .format(IP, PORT)) notify( "Serving <b>uLogMe</b> on a <i>HTTPS</i> server, see it locally on 'https://{}:{}' ..." .format(IP, PORT), icon="terminal") # DEBUG httpd.serve_forever() except socket.error as e: if e.errno == 98:
# seprating input into key and value x = temp[:1] y = temp[2:] # check if key is in data if x in jsonFile: jsonFile[x] = y # write the changes to file json.dump(jsonFile) else: error = "NOT FOUND!" self.wfile.write(bytes(error, 'utf-8')) self.send_response(404) # DELETE method defination def do_DELETE(self): temp = self._set_headers() # check if the key is present in the dictionary if temp in jsonFile: del jsonFile[temp] # write the changes to json file json.dump(jsonFile) else: error = "NOT FOUND!" self.wfile.write(bytes(error, 'utf-8')) self.send_response(404) # Server Initialization server = HTTPServer(('127.0.0.1', 8000), ServiceHandler) print('Server initialized at 127.0.0.1:8000') server.serve_forever()
def main(): httpd = HTTPServer(('localhost', 8000), RequestHandler) httpd.serve_forever()
content_type = "text/html" response_content = open('.' + self.path) response_content = response_content.read() else: content_type = "text/plain" response_content = "404 Not Found" elif re.findall(r'^\/api\/', self.path): # API 接口 filepath = Path('.' + self.path + '.py') if filepath.is_file(): content_type = "text/html" controller = self.path.split('/')[2] module = __import__('api.' + controller) response_content = eval('module.' + controller + '.index()') else: content_type = "text/plain" response_content = "404 Not Found" else: content_type = "text/plain" response_content = "404 Not Found" self.send_response(status) self.send_header('Content-type', content_type) self.end_headers() return bytes(response_content, "UTF-8") with HTTPServer(('', serverPort), handler) as server: print('[37;45m 启动HTTP 服务[0m 访问URL: localhost:' + str(serverPort)) server.serve_forever()
return log_parse(filename, 1, r'\d+\.\d+', 'noise') def get_log_list(self): filenames = glob.glob('**/*_201*/log.txt', recursive=True) filenames.sort(key=lambda x: int(x[-20:-8]), reverse=True) for i in range(len(filenames)): # filenames[i] = filenames[i][:-8] + '.png' filenames[i] = filenames[i][:-8] + '.info' return filenames if __name__ == '__main__': import sys if sys.version_info[1] > 5: with HTTPServer(('', PORT_NUMBER), myHandler) as my_server: # Create a web server and define the handler to manage the incoming request print('Started httpserver on port ', PORT_NUMBER) # Wait forever for incoming htto requests my_server.serve_forever() elif True: my_server = HTTPServer(('', PORT_NUMBER), myHandler) # Create a web server and define the handler to manage the incoming request print('Started httpserver on port ', PORT_NUMBER) # Wait forever for incoming htto requests my_server.serve_forever() elif False: filenames = glob.glob('**/*_*/log.txt', recursive=True)
def run(port=9797): server_address = ('', port) httpd = HTTPServer(server_address, Server) print('Starting meteo.lt bridge on port %d...' % port) httpd.serve_forever()
# Escape HTML tags in the message so users can't break world+dog. message = message.replace("<", "<") # Store it in memory. memory.append(message) # 1. Send a 303 redirect back to the root page. self.send_response(303) self.send_header('Location', '/') self.end_headers() def do_GET(self): # First, send a 200 OK response. self.send_response(200) # Then send headers. self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() # 2. Put the response together out of the form and the stored messages. # Then encode and send the form. mesg = form.format("\n".join(memory)) self.wfile.write(mesg.encode()) # 3. Send the response. if __name__ == '__main__': server_address = ('', 8000) httpd = HTTPServer(server_address, MessageHandler) httpd.serve_forever()
# Decode the form data. length = int(self.headers.get('Content-length', 0)) body = self.rfile.read(length).decode() params = parse_qs(body) try: # data to be sent to api restaurant_id = params["restaurant_id"][0] data = {"is_favorite": bool(int(params["is_favorite"][0]))} url = API_ENDPOINT + "restaurants/" + restaurant_id + "/" print(url) r = requests.put(url, json.dumps(data)) print(r.text) self.send_response(202) self.send_header('Content-type', 'text/html') self.end_headers() except Exception as e: err = str(e) print("Bad form. Missing " + err + ".") self.send_response(304) self.send_header('Content-type', 'text/html') self.end_headers() if __name__ == '__main__': port = int(os.environ.get('PORT', PORT)) # Use PORT if it's there. server_address = ('', port) httpd = HTTPServer(server_address, PostHandler) httpd.serve_forever()
from http.server import HTTPServer, BaseHTTPRequestHandler class Serv(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.path = '/index.html' try: file_to_open = open(self.path[1:]).read() self.send_response(200) except: file_to_open = "File not found" self.send_response(404) self.end_headers() self.wfile.write(bytes(file_to_open, 'utf-8')) httpd = HTTPServer(('localhost', 8080), Serv) httpd.serve_forever()
def create_page(self): values = { 'date_time': self.date_time_string(), 'client_host': self.client_address[0], 'client_port': self.client_address[1], 'command': self.command, 'path': self.path } page = self.Page.format(**values) return page def send_content(self, content, status=200): self.send_response(status) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) def run_cgi(self, full_path): data = subprocess.Popen('python ' + full_path, stdout=subprocess.PIPE, shell=True).stdout.read() self.send_content(data) #---------------------------------------------------------------------- if __name__ == '__main__': serverAddress = ('', 8080) server = HTTPServer(serverAddress, RequestHandler) server.serve_forever()
from http.server import SimpleHTTPRequestHandler, HTTPServer server = HTTPServer(('', 8000), SimpleHTTPRequestHandler) server.serve_forever()
if self.path.endswith(".css"): mimetype = 'text/css' sendReply = True if sendReply == True: #Open the static file requested and send it f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() self.wfile.write(bytes(f.read(), 'utf8')) f.close() return except IOError: self.send_error(404, 'File Not Found: %s' % self.path) try: #Create a web server and define the handler to manage the #incoming request PORT_NUMBER = int(os.environ.get('PORT', 8080)) server = HTTPServer(('', PORT_NUMBER), myHandler) print('Started httpserver on port ', PORT_NUMBER) #Wait forever for incoming htto requests server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down the web server') server.socket.close()
from http.server import HTTPServer, CGIHTTPRequestHandler server_address = ("", 2002) httpd = HTTPServer(server_address, CGIHTTPRequestHandler) httpd.serve_forever()
# Look for a cookie in the request. if 'cookie' in self.headers: try: # Extract and decode the cookie. c = cookies.SimpleCookie(self.headers['cookie']) name = c['yourname'].value # Craft a message, escaping any HTML special chars in name. message = "Hey there, " + html_escape(name) except (KeyError, cookies.CookieError) as e: message = "I'm not sure who you are!" print(e) # First, send a 200 OK response. self.send_response(200) # Then send headers. self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() # Send the form with the message in it. mesg = form.format(message) self.wfile.write(mesg.encode()) if __name__ == '__main__': server_address = ('', 8000) httpd = HTTPServer(server_address, NameHandler) httpd.serve_forever()
"""Simple script to redirect HTTP requests to HTTPS (or any other URL).""" from http.server import HTTPServer, BaseHTTPRequestHandler destination = "https://shove.cc" # from https://stackoverflow.com/a/47084250/13216113 class RequestRedirect(BaseHTTPRequestHandler): def do_GET(self): self.send_response(301) self.send_header("Location", destination) self.end_headers() client_ip, client_port = self.client_address print(f"Redirected {client_ip}:{client_port}") print(f"Redirecting HTTP traffic to {destination}!") HTTPServer(("", 80), RequestRedirect).serve_forever()
def main(): httpd = HTTPServer(('0.0.0.0', 9100), Handler) httpd.serve_forever()
from http.server import HTTPServer, BaseHTTPRequestHandler class Serv(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.path = '/index.html' try: file_to_open = open(self.path[1:]).read() self.send_response(200) except: file_to_open = "File not found" self.send_response(404) self.end_headers() self.wfile.write(bytes(file_to_open, 'utf-8')) httpd = HTTPServer(('aatiwarishub-python-linux.azurewebsites.net', 8080), Serv) httpd.serve_forever()