Python SocketServer.BaseRequestHandler() Examples

The following are 20 code examples of SocketServer.BaseRequestHandler(). 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: test_graphite_bridge.py    From client_python with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.registry = CollectorRegistry()

        self.data = ''

        class TCPHandler(SocketServer.BaseRequestHandler):
            def handle(s):
                self.data = s.request.recv(1024)

        server = SocketServer.TCPServer(('', 0), TCPHandler)

        class ServingThread(threading.Thread):
            def run(self):
                server.handle_request()
                server.socket.close()

        self.t = ServingThread()
        self.t.start()

        # Explicitly use localhost as the target host, since connecting to 0.0.0.0 fails on Windows
        address = ('localhost', server.server_address[1])
        self.gb = GraphiteBridge(address, self.registry, _timer=fake_timer) 
Example #3
Source File: recipe-577212.py    From code with MIT License 6 votes vote down vote up
def __init__(self):
        
        self.CryptoArgs =  dict()
        self.CryptoArgs['INITKEY']       = "My initial key"
        self.CryptoArgs['DEBUG']         = False
        self.CryptoArgs['CYCLES']        = 3
        self.CryptoArgs['BLOCK_SZ']      = 20
        self.CryptoArgs['KEY_ADV']       = 5
        self.CryptoArgs['KEY_MAGNITUDE'] = 1
        
        SimpleCryptSocketExt.__init__(self, self.CryptoArgs)
        
        self.InBoundData    = ""
        self.OutBoundData   = ""
        
        #self.salt_method  = "Simple"
        #self.salt_method  = "NTP"
        #self.salt_method  = "PrevData"
        
    
#####################################################################################            
   
    
#####################################################################################
#Class to handle Server coms overriding BaseRequestHandler handle method 
Example #4
Source File: testrun.py    From honeypot with GNU General Public License v2.0 6 votes vote down vote up
def run_udp(realport, fakeport, handler):
	class SingleUDPHandler(SocketServer.BaseRequestHandler):
		def handle(self):
			srcaddr, srcport = self.client_address
			print("Packet from {}:{}".format(srcaddr, srcport))
			handler(self.request[1], self.request[0], self.client_address, fakeport)

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

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

	server = SimpleServer(('127.0.0.1', realport), SingleUDPHandler)
	try:
		server.serve_forever()
	except KeyboardInterrupt:
		sys.exit(0) 
Example #5
Source File: EchoServer.py    From python-scripts with GNU General Public License v3.0 5 votes vote down vote up
def finish(self):
        self.logger.debug('finish')
        return SocketServer.BaseRequestHandler.finish(self) 
Example #6
Source File: EchoServer.py    From python-scripts with GNU General Public License v3.0 5 votes vote down vote up
def setup(self):
        self.logger.debug('setup')
        return SocketServer.BaseRequestHandler.setup(self) 
Example #7
Source File: EchoServer.py    From python-scripts with GNU General Public License v3.0 5 votes vote down vote up
def __init__ (self, request, client_address, server):
        self.logger = logging.getLogger('EchoRequestHandler')
        self.logger.debug('__init__')
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
        return 
Example #8
Source File: conftest.py    From libnl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def tcp_server(request):
    """Start a TCP server in a thread."""
    data = list()

    class Getter(object):
        def __init__(self, t, s, d):
            self.thread = t
            self.server = s
            self._data = d

        @property
        def data(self):
            for i in range(50):
                if self._data:
                    break
                time.sleep(0.1)
            return self._data

    class TCPHandler(socketserver.BaseRequestHandler):
        def handle(self):
            data.append(self.request.recv(25))

    server = socketserver.TCPServer(('', 0), TCPHandler)
    thread = threading.Thread(target=server.serve_forever)
    thread.daemon = True
    thread.start()

    def fin():
        server.socket.close()
        server.shutdown()
        for _ in range(5):
            if not thread.is_alive():
                break
            time.sleep(0.2)
        assert not thread.is_alive()
    request.addfinalizer(fin)

    return Getter(thread, server, data) 
Example #9
Source File: rpc.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, sock, addr, svr):
        svr.current_handler = self ## cgt xxx
        SocketIO.__init__(self, sock)
        SocketServer.BaseRequestHandler.__init__(self, sock, addr, svr) 
Example #10
Source File: socksserver.py    From Exchange2domain with MIT License 5 votes vote down vote up
def __init__(self, request, client_address, server):
        self.__socksServer = server
        self.__ip, self.__port = client_address
        self.__connSocket= request
        self.__socksVersion = 5
        self.targetHost = None
        self.targetPort = None
        self.__NBSession= None
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #11
Source File: tcp.py    From ryu with Apache License 2.0 5 votes vote down vote up
def create_length_prefixed_tcp_handler():
    queue = Queue()
    class LengthPrefixedTcpHandler(BaseRequestHandler):
        def handle(self):
            #msg = _read_length_prefixed_msg(self.request)
            # this will run inside a new thread
            self.request.send("hello\n")
            while True:
                b = _read_n_bytes(self.request, 10)
                self.request.send("you sent: %s" % b)
                queue.put(b)

    return queue, LengthPrefixedTcpHandler 
Example #12
Source File: socksserver.py    From cracke-dit with MIT License 5 votes vote down vote up
def __init__(self, request, client_address, server):
        self.__socksServer = server
        self.__ip, self.__port = client_address
        self.__connSocket= request
        self.__socksVersion = 5
        self.targetHost = None
        self.targetPort = None
        self.__NBSession= None
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #13
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def __init__(self, sock, addr, svr):
        svr.current_handler = self ## cgt xxx
        SocketIO.__init__(self, sock)
        SocketServer.BaseRequestHandler.__init__(self, sock, addr, svr) 
Example #14
Source File: rpc.py    From BinderFilter with MIT License 5 votes vote down vote up
def __init__(self, sock, addr, svr):
        svr.current_handler = self ## cgt xxx
        SocketIO.__init__(self, sock)
        SocketServer.BaseRequestHandler.__init__(self, sock, addr, svr) 
Example #15
Source File: ggposrv.py    From ggposrv with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, request, client_address, server):
		self.quark=''
		SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #16
Source File: ggposrv.py    From ggposrv with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, request, client_address, server):
		self.nick = None		# Client's currently registered nickname
		self.host = client_address	# Client's hostname / ip.
		self.status = 0			# Client's status (0=available, 1=away, 2=playing)
		self.clienttype = None		# can be: player(fba), spectator(fba) or client
		self.previous_status = None	# Client's previous status (0=available, 1=away, 2=playing)
		self.opponent = None		# Client's opponent
		self.quark = None		# Client's quark (in-game uri)
		self.fbaport = 0		# Emulator's fbaport
		self.side = 0			# Client's side: 1=P1, 2=P2 (0=spectator before savestate, 3=spectator after savestate)
		self.port = 6009		# Client's port
		self.city = "null"		# Client's city
		self.country = "null"		# Client's country
		self.cc = "null"		# Client's country code
		self.lastmsgtime = 0		# timestamp of the last chat message
		self.challengetime = 0		# timestamp of the last challenge
		self.lastmsg = ''		# last chat message
		self.spamhit = 0		# how many times has been warned for spam
		self.useports = False		# set to true when we have potential problems with NAT traversal
		self.version = 0		# client version
		self.warnmsg = ''		# Warning message (shown after match)
		self.turboflag = 0		# turbo flag helper
		self.send_queue = []		# Messages to send to client (strings)
		self.channel = GGPOChannel("lobby",'', "The Lobby")	# Channel the client is in
		self.challenging = {}		# users (GGPOClient instances) that this client is challenging by host

		try:
			set_keepalive_linux(request)
		except:
			pass
		SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #17
Source File: ssh_forward.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
		self.server = args[2]
		self.chain_host = self.server.remote_server[0]
		self.chain_port = self.server.remote_server[1]
		self.ssh_transport = self.server.ssh_transport
		socketserver.BaseRequestHandler.__init__(self, *args, **kwargs) 
Example #18
Source File: tcpportlistener.py    From SecPi with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request, client_address, server):
		SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
		return 
Example #19
Source File: telnetsrvlib.py    From hontel with MIT License 4 votes vote down vote up
def __init__(self, request, client_address, server):
        """Constructor.

        When called without arguments, create an unconnected instance.
        With a hostname argument, it connects the instance; a port
        number is optional.
        """
        # Am I doing the echoing?
        self.DOECHO = True
        # What opts have I sent DO/DONT for and what did I send?
        self.DOOPTS = {}
        # What opts have I sent WILL/WONT for and what did I send?
        self.WILLOPTS = {}

        # What commands does this CLI support
        self.COMMANDS = {}
        self.sock = None    # TCP socket
        self.rawq = ''      # Raw input string
        self.sbdataq = ''   # Sub-Neg string
        self.eof = 0        # Has EOF been reached?
        self.iacseq = ''    # Buffer for IAC sequence.
        self.sb = 0     # Flag for SB and SE sequence.
        self.history = []   # Command history
        self.RUNSHELL = True
        # A little magic - Everything called cmdXXX is a command
        # Also, check for decorated functions
        for k in dir(self):
            method = getattr(self, k)
            try:
                name = method.command_name
            except:
                if k[:3] == 'cmd':
                    name = k[3:]
                else:
                    continue
            
            name = name.upper()
            self.COMMANDS[name] = method
            for alias in getattr(method, "aliases", []):
                self.COMMANDS[alias.upper()] = self.COMMANDS[name]
                    
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) 
Example #20
Source File: test_supervisor_logging.py    From supervisor-logging with Apache License 2.0 4 votes vote down vote up
def test_logging(self):
        """
        Test logging.
        """

        messages = []

        class SyslogHandler(socketserver.BaseRequestHandler):
            """
            Save received messages.
            """

            def handle(self):
                messages.append(self.request[0].strip().decode())

        syslog = socketserver.UDPServer(('0.0.0.0', 0), SyslogHandler)
        try:
            threading.Thread(target=syslog.serve_forever).start()

            env = os.environ.copy()
            env['SYSLOG_SERVER'] = syslog.server_address[0]
            env['SYSLOG_PORT'] = str(syslog.server_address[1])
            env['SYSLOG_PROTO'] = 'udp'

            mydir = os.path.dirname(__file__)

            supervisor = subprocess.Popen(
                ['supervisord', '-c', os.path.join(mydir, 'supervisord.conf')],
                env=env,
            )
            try:

                sleep(3)

                pid = subprocess.check_output(
                    ['supervisorctl', 'pid', 'messages']
                ).decode().strip()

                sleep(8)

                self.assertEqual(
                    list(map(strip_volatile, messages)),
                    ['<14>DATE HOST messages[{pid}]: Test {i} \n\x00'.format(
                        pid=pid,
                        i=i)
                     for i in range(4)]
                )
            finally:
                supervisor.terminate()

        finally:
            syslog.shutdown()