Python SocketServer.TCPServer() Examples

The following are 30 code examples of SocketServer.TCPServer(). 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 SocketServer , or try the search function .
Example #1
Source File: testrun.py    From honeypot with GNU General Public License v2.0 8 votes vote down vote up
def run_tcp(realport, fakeport, handler):
	class SingleTCPHandler(SocketServer.BaseRequestHandler):
		def handle(self):
			srcaddr, srcport = self.request.getpeername()
			print("Connection from {}:{}".format(srcaddr, srcport))
			handler(self.request, fakeport)

	class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
		daemon_threads = True
		allow_reuse_address = True

		def __init__(self, server_address, RequestHandlerClass):
			SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

	server = SimpleServer(('127.0.0.1', realport), SingleTCPHandler)
	try:
		server.serve_forever()
	except KeyboardInterrupt:
		sys.exit(0) 
Example #2
Source File: streamserver.py    From pulseaudio-dlna with GNU General Public License v3.0 7 votes vote down vote up
def run(self):
        self.allow_reuse_address = True
        self.daemon_threads = True
        try:
            SocketServer.TCPServer.__init__(
                self, (self.ip or '', self.port), StreamRequestHandler)
        except socket.error:
            logger.critical(
                'The streaming server could not bind to your specified port '
                '({port}). Perhaps this is already in use? The application '
                'cannot work properly!'.format(port=self.port))
            sys.exit(1)

        signal.signal(signal.SIGTERM, self.shutdown)
        if self.proc_title:
            setproctitle.setproctitle(self.proc_title)
        self.serve_forever() 
Example #3
Source File: test_socketserver.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_shutdown(self):
        # Issue #2302: shutdown() should always succeed in making an
        # other thread leave serve_forever().
        class MyServer(SocketServer.TCPServer):
            pass

        class MyHandler(SocketServer.StreamRequestHandler):
            pass

        threads = []
        for i in range(20):
            s = MyServer((HOST, 0), MyHandler)
            t = threading.Thread(
                name='MyServer serving',
                target=s.serve_forever,
                kwargs={'poll_interval':0.01})
            t.daemon = True  # In case this function raises.
            threads.append((t, s))
        for t, s in threads:
            t.start()
            s.shutdown()
        for t, s in threads:
            t.join() 
Example #4
Source File: httprelayserver.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, server_address, RequestHandlerClass, config):
            self.config = config
            SocketServer.TCPServer.__init__(self,server_address, RequestHandlerClass) 
Example #5
Source File: dnschef.py    From break-fast-serial with MIT License 6 votes vote down vote up
def __init__(self, server_address, RequestHandlerClass, nametodns, nameservers, ipv6, log):
        self.nametodns   = nametodns
        self.nameservers = nameservers
        self.ipv6        = ipv6
        self.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET
        self.log = log

        SocketServer.TCPServer.__init__(self,server_address,RequestHandlerClass) 
        
# Initialize and start the DNS Server 
Example #6
Source File: test_socketserver.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_shutdown_request_called_if_verify_request_false(self):
        # Issue #26309: BaseServer should call shutdown_request even if
        # verify_request is False

        class MyServer(SocketServer.TCPServer):
            def verify_request(self, request, client_address):
                return False

            shutdown_called = 0
            def shutdown_request(self, request):
                self.shutdown_called += 1
                SocketServer.TCPServer.shutdown_request(self, request)

        server = MyServer((HOST, 0), SocketServer.StreamRequestHandler)
        s = socket.socket(server.address_family, socket.SOCK_STREAM)
        s.connect(server.server_address)
        s.close()
        server.handle_request()
        self.assertEqual(server.shutdown_called, 1)
        close_server(server) 
Example #7
Source File: xml_file_server.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def serve(port=PORT):
    '''Serves test XML files over HTTP'''
    
    # Make sure we serve from the tests' XML directory
    os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                          'xml'))

    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    
    class TestServer(SocketServer.TCPServer):
        allow_reuse_address = True
    
    httpd = TestServer(("", PORT), Handler)
    
    print 'Serving test HTTP server at port', PORT

    httpd_thread = Thread(target=httpd.serve_forever)
    httpd_thread.setDaemon(True)
    httpd_thread.start() 
Example #8
Source File: mock_ckan.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def serve(port=PORT):
    '''Runs a CKAN-alike app (over HTTP) that is used for harvesting tests'''

    # Choose the directory to serve files from
    #os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)),
    #                      'mock_ckan_files'))

    class TestServer(SocketServer.TCPServer):
        allow_reuse_address = True

    httpd = TestServer(("", PORT), MockCkanHandler)

    print 'Serving test HTTP server at port', PORT

    httpd_thread = Thread(target=httpd.serve_forever)
    httpd_thread.setDaemon(True)
    httpd_thread.start() 
Example #9
Source File: test_socketserver.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_shutdown(self):
        # Issue #2302: shutdown() should always succeed in making an
        # other thread leave serve_forever().
        class MyServer(SocketServer.TCPServer):
            pass

        class MyHandler(SocketServer.StreamRequestHandler):
            pass

        threads = []
        for i in range(20):
            s = MyServer((HOST, 0), MyHandler)
            t = threading.Thread(
                name='MyServer serving',
                target=s.serve_forever,
                kwargs={'poll_interval':0.01})
            t.daemon = True  # In case this function raises.
            threads.append((t, s))
        for t, s in threads:
            t.start()
            s.shutdown()
        for t, s in threads:
            t.join() 
Example #10
Source File: socksserver.py    From cracke-dit with MIT License 6 votes vote down vote up
def __init__(self, server_address=('0.0.0.0', 1080), handler_class=SocksRequestHandler):
        LOG.info('SOCKS proxy started. Listening at port %d', server_address[1] )

        self.activeRelays = {}
        self.socksPlugins = {}
        SocketServer.TCPServer.allow_reuse_address = True
        SocketServer.TCPServer.__init__(self, server_address, handler_class)

        # Let's register the socksplugins plugins we have
        from impacket.examples.ntlmrelayx.servers.socksplugins import SOCKS_RELAYS

        for relay in SOCKS_RELAYS:
            LOG.info('Plugin %s loaded..' % relay.PLUGIN_NAME)
            self.socksPlugins[relay.getProtocolPort()] = relay

        # Let's create a timer to keep the connections up.
        self.__timer = RepeatedTimer(300.0, keepAliveTimer, self) 
Example #11
Source File: rpc.py    From BinderFilter with MIT License 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print>>erf, '\n' + '-'*40
            print>>erf, 'Unhandled server exception!'
            print>>erf, 'Thread: %s' % threading.currentThread().getName()
            print>>erf, 'Client Address: ', client_address
            print>>erf, 'Request: ', repr(request)
            traceback.print_exc(file=erf)
            print>>erf, '\n*** Unrecoverable, server exiting!'
            print>>erf, '-'*40
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example #12
Source File: rpc.py    From oss-ftp with MIT License 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print>>erf, '\n' + '-'*40
            print>>erf, 'Unhandled server exception!'
            print>>erf, 'Thread: %s' % threading.currentThread().getName()
            print>>erf, 'Client Address: ', client_address
            print>>erf, 'Request: ', repr(request)
            traceback.print_exc(file=erf)
            print>>erf, '\n*** Unrecoverable, server exiting!'
            print>>erf, '-'*40
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example #13
Source File: demo_server.py    From ZASR_tensorflow with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 server_address,
                 RequestHandlerClass,
                 speech_save_dir,
                 audio_process_handler,
                 bind_and_activate=True):
        self.speech_save_dir = speech_save_dir
        self.audio_process_handler = audio_process_handler
        SocketServer.TCPServer.__init__(
            self, server_address, RequestHandlerClass, bind_and_activate=True) 
Example #14
Source File: DNSListener.py    From flare-fakenet-ng with Apache License 2.0 5 votes vote down vote up
def __init__(self, server_address, config, logger, RequestHandlerClass):
        self.config = config
        self.logger = logger
        SocketServer.TCPServer.__init__(self,server_address,RequestHandlerClass) 
Example #15
Source File: assistent.py    From taketv with MIT License 5 votes vote down vote up
def upServer(port=3000):
	Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
	httpd = SocketServer.TCPServer(("", int(port)), Handler)
	ip = getIpServer()
	print "[*] Servidor Local Levantado en:"
	print "[*] http://"+ip+":"+str(port)+"/"
	print ""
	print "-------------------------------------------------------------------------------------------"
	print listfile(ip,port)
	print "-------------------------------------------------------------------------------------------"
	print "Ctrl + C para Salir."
	print ""
	httpd.serve_forever() 
Example #16
Source File: BaseHTTPServer.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def server_bind(self):
        """Override server_bind to store the server name."""
        SocketServer.TCPServer.server_bind(self)
        host, port = self.socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port 
Example #17
Source File: SimpleXMLRPCServer.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        # [Bug #1222790] If possible, set close-on-exec flag; if a
        # method spawns a subprocess, the subprocess shouldn't have
        # the listening socket open.
        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example #18
Source File: test_static_webgl_library.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def try_static_webgl_library():
    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))

    # Change to lib/ which contains "libtvm_runtime.bc".
    os.chdir(os.path.join(curr_path, "../../lib"))

    # Create OpenGL module.
    n = tvm.var("n")
    A = tvm.placeholder((n,), name='A', dtype="float")
    B = tvm.compute((n,), lambda *i: A[i], name="B")

    s = tvm.create_schedule(B.op)
    s[B].opengl()

    target_host = "llvm -target=asmjs-unknown-emscripten -system-lib"
    f = tvm.build(s, [A, B], name="identity", target="opengl",
                  target_host=target_host)

    # Create a JS library that contains both the module and the tvm runtime.
    path_dso = "identity_static.js"
    f.export_library(path_dso, emscripten.create_js, options=[
        "-s", "USE_GLFW=3",
        "-s", "USE_WEBGL2=1",
        "-lglfw",
    ])

    # Create "tvm_runtime.js" and "identity_static.html" in lib/
    shutil.copyfile(os.path.join(curr_path, "../../web/tvm_runtime.js"),
                    "tvm_runtime.js")
    shutil.copyfile(os.path.join(curr_path, "test_static_webgl_library.html"),
                    "identity_static.html")

    port = 8080
    handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", port), handler)
    print("Please open http://localhost:" + str(port) + "/identity_static.html")
    httpd.serve_forever() 
Example #19
Source File: core.py    From quantipy with MIT License 5 votes vote down vote up
def shutdown_server(server_target):
    """ Spawns a thread that triggers the TCPServer.shutdown method """
    assassin = threading.Thread(target=server_target.shutdown)
    assassin.daemon = True
    assassin.start() 
Example #20
Source File: socksserver.py    From cracke-dit with MIT License 5 votes vote down vote up
def shutdown(self):
        self.__timer.stop()
        return SocketServer.TCPServer.shutdown(self) 
Example #21
Source File: core.py    From quantipy with MIT License 5 votes vote down vote up
def start_server(host, port, handler):
    """ Starts a SimpleHTTPServer with a speciffic handler.

        The handler needs to trigger the TCPServer.shutdown method or 
        else the server runs until doomsday.
    """
    httpd = SocketServer.TCPServer((host, port), handler)
    print_server_message(host, port, handler)
    httpd.serve_forever() # This is stopped by using the handler 
Example #22
Source File: httprelayserver.py    From cracke-dit with MIT License 5 votes vote down vote up
def __init__(self, server_address, RequestHandlerClass, config):
            self.config = config
            SocketServer.TCPServer.__init__(self,server_address, RequestHandlerClass) 
Example #23
Source File: challenge.py    From fbctf-2019-challenges with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(TCPServer, self).__init__(*args, **kwargs)
        self._start_time = time.time()
        self._client_ratelimit = {} 
Example #24
Source File: myssl.py    From z-ssl-proxy with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 server_address,
                 RequestHandlerClass,
                 certfile = None,
                 keyfile = None,
                 ssl_version=ssl.PROTOCOL_SSLv23,
                 bind_and_activate=True):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
        if certfile or keyfile:
            self.socket = ssl.wrap_socket(self.socket,
                                         server_side=True,
                                         certfile = certfile,
                                         keyfile = keyfile,
                                         ssl_version = ssl_version) 
Example #25
Source File: challenge.py    From fbctf-2019-challenges with MIT License 5 votes vote down vote up
def process_request(self, request, client_address):
        children = len(self.active_children or [])
        print('Accepting Connection, {}/{} ({})'.format(
            children+1,
            self.max_children,
            client_address,
        ))
        return super(TCPServer, self).process_request(request, client_address) 
Example #26
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def get_request(self):
        "Override TCPServer method, return already connected socket"
        return self.socket, self.server_address 
Example #27
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def server_activate(self):
        """Override TCPServer method, connect() instead of listen()

        Due to the reversed connection, self.server_address is actually the
        address of the Idle Client to which we are connecting.

        """
        self.socket.connect(self.server_address) 
Example #28
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def server_bind(self):
        "Override TCPServer method, no bind() phase for connecting entity"
        pass 
Example #29
Source File: BaseHTTPServer.py    From oss-ftp with MIT License 5 votes vote down vote up
def server_bind(self):
        """Override server_bind to store the server name."""
        SocketServer.TCPServer.server_bind(self)
        host, port = self.socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port 
Example #30
Source File: socks5proxy.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, rpyc_client=None, module=None):
		self.rpyc_client=rpyc_client
		self.module=module
		SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)