当前位置: 首页>>代码示例>>Python>>正文


Python backdoor.BackdoorServer类代码示例

本文整理汇总了Python中gevent.backdoor.BackdoorServer的典型用法代码示例。如果您正苦于以下问题:Python BackdoorServer类的具体用法?Python BackdoorServer怎么用?Python BackdoorServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了BackdoorServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Warpgate

class Warpgate(object):

    def init(self):
        import options
        from UnityEngine import Debug

        L = lambda s: Debug.Log("PyWrap: " + s)
        L("init")

        self.events = []

        # should set them
        options.no_update
        options.show_hidden_mode

        options.freeplay = False

        if options.no_update:
            import autoupdate
            autoupdate.Autoupdate = autoupdate.DummyAutoupdate

        L("before gevent")
        from gevent import monkey
        monkey.patch_socket()
        monkey.patch_os()
        monkey.patch_select()
        L("after gevent")

        from game import autoenv
        autoenv.init('Client')

        import thb.ui.ui_meta  # noqa, init ui_meta

        from client.core.executive import Executive
        self.executive = ExecutiveWrapper(Executive, self)

    def get_events(self):
        l = self.events
        self.events = []
        return l

    def start_backdoor(self):
        from gevent.backdoor import BackdoorServer
        import gevent
        self.bds = BackdoorServer(('127.0.0.1', 12345))
        self.gr_bds = gevent.spawn(self.bds.serve_forever)

    def stop_backdoor(self):
        self.gr_bds.kill()
        self.bds.close()

    def shutdown(self):
        from client.core.executive import Executive
        if Executive.state == 'connected':
            Executive.disconnect()

    def queue_system_event(self, evt_name, arg=None):
        self.events.append(('system_event', evt_name, arg))
开发者ID:feisuzhu,项目名称:thbattle,代码行数:58,代码来源:warpgate.py

示例2: startbackdoor

def startbackdoor(host=None, port=8998):
    if get_config('DONT_USE_GEVENT'):
        raise('Backdoor is not available')
    if host is None:
        host=HOST
    from gevent.backdoor import BackdoorServer
    print('Backdoor is on %s:%s' % (host, port))
    bs = BackdoorServer((host, port), locals())
    bs.start()
开发者ID:SandStormHoldings,项目名称:NoodlesFramework,代码行数:9,代码来源:app.py

示例3: BackdoorPlugin

class BackdoorPlugin(BotPlugin):
	name = 'backdoor'
	defaults = {
		'port': 1234,
	}

	def init(self):
		self.server = BackdoorServer(('localhost', self.config.port), locals={
			'clients': clients,
		})
		self.server.start()

	def cleanup(self):
		super(BackdoorPlugin, self).cleanup()
		self.server.stop()
开发者ID:ekimekim,项目名称:ekimbot,代码行数:15,代码来源:backdoor.py

示例4: __init__

    def __init__(self, name='', devices=(), backdoor=None):
        self.name = name
        self._log = logging.getLogger('{0}.{1}'.format(_log.name, name))
        self._log.info('Bootstraping server')
        if backdoor:
            from gevent.backdoor import BackdoorServer
            banner = 'Welcome to Bliss emulator server console.\n' \
                     'My name is {0!r}. You can access me through the ' \
                     '\'server()\' function. Have fun!'.format(name)
            self.backdoor = BackdoorServer(backdoor, banner=banner,
                                           locals=dict(server=weakref.ref(self)))
            self.backdoor.start()
            self._log.info('Backdoor opened at %r', backdoor)

        else:
            self._log.info('no backdoor declared')

        self.devices = {}
        for device in devices:
            try:
                self.create_device(device)
            except Exception as error:
                dname = device.get('name', device.get('class', 'unknown'))
                self._log.error('error creating device %s (will not be available): %s',
                                dname, error)
                self._log.debug('details: %s', error, exc_info=1)
开发者ID:tiagocoutinho,项目名称:bliss,代码行数:26,代码来源:emulator.py

示例5: start_backdoor

    def start_backdoor(self):
        self.backdoor_server = BackdoorServer(
            ('127.0.0.1', 9999),
            banner='DebugService backdoor server',
            locals={
                'dispatcher': self.dispatcher
            }
        )

        gevent.spawn(self.backdoor_server.serve_forever)
开发者ID:erinix,项目名称:middleware,代码行数:10,代码来源:services.py

示例6: start_backdoor

    def start_backdoor(self):
        if not self.gevent:
            raise RpcException(errno.ENOTSUP, 'Not supported')

        from gevent import spawn
        from gevent.backdoor import BackdoorServer
        self.backdoor_server = BackdoorServer(
            ('127.0.0.1', 9999),
            banner='DebugService backdoor server',
            locals=self.backdoor_locals
        )

        spawn(self.backdoor_server.serve_forever())
开发者ID:650elx,项目名称:middleware,代码行数:13,代码来源:debug.py

示例7: run

    def run(self, auto_join=False):
        """
            Runs Dissonance, loading all the modules, starting the web service, and starting the adapter.

            If auto_join=True, this function will not return, and will run until dissonance stops if starting dissonance from
            outside of a greenlet.

        """
        if self.running:
            raise RuntimeError("Dissonance is already running!")

        logger.info("Starting Dissonance v%s", self.version)

        logger.info("Starting storage %s", self._storage)
        self._storage.start()

        logger.info("Loading modules")
        self.modules.load_all()

        if getattr(self.config, 'web', False) or str(self._opts.get('web', False)).upper() == 'TRUE':
            self._web = Web(self, EnvFallbackDict('web', getattr(self.config, 'web_opts', {})))
            self._web.start()

        if getattr(self.config, 'manhole', False):
            from gevent.backdoor import BackdoorServer
            manhole_opts = EnvFallbackDict('manhole', getattr(self.config, 'manhole_opts', {}))
            self._manhole = BackdoorServer((
                manhole_opts.get('listen_host', '127.0.0.1'),
                int(manhole_opts.get('listen_port', 9001))
            ), locals={
                'client': self.client
            })

            self._manhole.start()

        logger.info("Attempting to log in as %s" % self._opts['email'])
        self.client.login(self._opts['email'], self._opts['password'])
        logger.info("Starting connection to Discord")
        self.client.start()
        self._storage_sync_periodic.start(right_away=False)
        self._stop_event.clear()

        # If we are the main greenlet, chances are we probably want to never return,
        # so the main greenlet won't exit, and tear down everything with it.
        if auto_join and gevent.get_hub().parent == gevent.getcurrent():
            self.join()
开发者ID:jhgg,项目名称:dissonance,代码行数:46,代码来源:dissonance.py

示例8: start_backdoor

    def start_backdoor(self, backlog=50):
        """Start a backdoor server on a local UNIX domain socket.

        """
        backdoor_path = self.get_backdoor_path()
        try:
            os.remove(backdoor_path)
        except OSError as error:
            if error.errno != errno.ENOENT:
                raise
        else:
            logger.warning("A backdoor socket has been found and deleted.")
        mkdir(os.path.dirname(backdoor_path))
        backdoor_sock = _socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        backdoor_sock.setblocking(0)
        backdoor_sock.bind(backdoor_path)
        user = pwd.getpwnam("cmsuser")
        # We would like to also set the user to "cmsuser" but only root
        # can do that. Therefore we limit ourselves to the group.
        os.chown(backdoor_path, os.getuid(), user.pw_gid)
        os.chmod(backdoor_path, 0o770)
        backdoor_sock.listen(backlog)
        self.backdoor = BackdoorServer(backdoor_sock, locals={'service': self})
        self.backdoor.start()
开发者ID:Karl-Krauth,项目名称:cms,代码行数:24,代码来源:service.py

示例9: Service


#.........这里部分代码省略.........

        # Wake up the run() cycle
        self.event.set()

    def get_backdoor_path(self):
        """Return the path for a UNIX domain socket to use as backdoor.

        """
        return os.path.join(config.run_dir, "%s_%d" % (self.name, self.shard))

    @rpc_method
    def start_backdoor(self, backlog=50):
        """Start a backdoor server on a local UNIX domain socket.

        """
        backdoor_path = self.get_backdoor_path()
        try:
            os.remove(backdoor_path)
        except OSError as error:
            if error.errno != errno.ENOENT:
                raise
        else:
            logger.warning("A backdoor socket has been found and deleted.")
        mkdir(os.path.dirname(backdoor_path))
        backdoor_sock = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
        backdoor_sock.setblocking(0)
        backdoor_sock.bind(backdoor_path)
        user = pwd.getpwnam("cmsuser")
        # We would like to also set the user to "cmsuser" but only root
        # can do that. Therefore we limit ourselves to the group.
        os.chown(backdoor_path, os.getuid(), user.pw_gid)
        os.chmod(backdoor_path, 0o770)
        backdoor_sock.listen(backlog)
        self.backdoor = BackdoorServer(backdoor_sock, locals={'service': self})
        self.backdoor.start()

    @rpc_method
    def stop_backdoor(self):
        """Stop a backdoor server started by start_backdoor.

        """
        if self.backdoor is not None:
            self.backdoor.stop()
        backdoor_path = self.get_backdoor_path()
        try:
            os.remove(backdoor_path)
        except OSError as error:
            if error.errno != errno.ENOENT:
                raise

    def run(self):
        """Starts the main loop of the service.

        return (bool): True if successful.

        """
        try:
            self.server.start()

        # This must come before socket.error, because socket.gaierror
        # extends socket.error
        except gevent.socket.gaierror:
            logger.critical("Service %s could not listen on "
                            "specified address, because it cannot "
                            "be resolved." % (self.name))
            return False
开发者ID:yunmanger1,项目名称:cms,代码行数:67,代码来源:GeventLibrary.py

示例10: init

	def init(self):
		self.server = BackdoorServer(('localhost', self.config.port), locals={
			'clients': clients,
		})
		self.server.start()
开发者ID:ekimekim,项目名称:ekimbot,代码行数:5,代码来源:backdoor.py

示例11: main

def main(stdscr, *args, **kwargs):
	global answer, feedback, candidates

	gevent.signal(signal.SIGUSR1, lambda *args: game_close.set()) # For standard/graceful restart
#	gevent.signal(signal.SIGINT, lambda *args: None) # Disable SIGINT
#	signal.signal(signal.SIGQUIT, signal.SIG_IGN) # Disable SIGQUIT
#	signal.signal(signal.SIGTSTP, signal.SIG_IGN) # Disable SIGTSTP

	logging.info("Window bounds: %s", stdscr.getmaxyx())

	backdoor = BackdoorServer(('0.0.0.0', 4200))
	backdoor.start()
	logging.info("Backdoor started")

	curses.curs_set(0) # Cursor invisible
	stdscr.nodelay(1) # Nonblocking input
	MAXY, MAXX = stdscr.getmaxyx()

	curses.init_pair(PAIR_MAIN, *DEFAULT_COLORS)
	curses.init_pair(PAIR_AI, curses.COLOR_RED, curses.COLOR_BLACK)
	curses.init_pair(PAIR_FEEDBACK, curses.COLOR_WHITE, curses.COLOR_BLACK)
	curses.init_pair(PAIR_TAGGED, curses.COLOR_YELLOW, curses.COLOR_BLACK)

	rightscr = stdscr.subwin(0, SPLIT)
	leftscr = stdscr.subwin(VERTSPLIT, SPLIT, 0, 0)

	logging.info("Right screen from %s, size %s", rightscr.getbegyx(), rightscr.getmaxyx())
	logging.info("Left screen from %s, size %s", leftscr.getbegyx(), leftscr.getmaxyx())

	feedback = SlowtypeWindow((VERTSPLIT, 1), (MAXY - VERTSPLIT - 1, SPLIT - 1))

	answer = random.choice(get_words(WORDS_PATH))
	candidates = get_closest(answer, WORDS_PATH, NUM_CANDIDATES - 1) + [answer]

	shuffle_main(leftscr, candidates)

	g_key_handler = spawn(key_handler, stdscr, leftscr)
	first_key.wait()
	g_chatter = spawn(timed_chat, rightscr, MAXY - 2)

	won = game_win_state.get()

	do_ai_fast.set()
	ai_done.wait()

	g_key_handler.kill()
	g_chatter.kill()
	feedback.wait()

	if not won:
		end(stdscr, "LOSS")

	attr = curses.color_pair(PAIR_MAIN)
	leftscr.move(0,0)
	leftscr.clear()
	leftscr.addstr("""WARNING
Experiment 203 (Synthetic Reasoning, Combat)
 has breached containment.
Please select a course of action.
 (1) Isolate system and scrub disks (This will
      destroy all research on Experiment 203)
 (2) Release remaining locks, allow experiment
      full access to base (MAY BE DANGEROUS)
 (3) Activate Emergency Base Procedure XK-682

""", attr)
	leftscr.refresh()

	first = True
	while 1:
		c = gevent_getch(sys.stdin, stdscr)
		if c == ord('1'):
			end(stdscr, "DESTROY")
		elif c == ord('2'):
			end(stdscr, "RELEASE")
		elif c == ord('3') and first:
			first = False
			logging.info("User attempted to arm the nukes")
			n = 3
			leftscr.addstr("Arming nuclear warheads.\nActivation in ", attr)
			y,x = leftscr.getyx()
			for i in range(n, -1, -1):
				leftscr.move(y,x)
				leftscr.addstr("%d seconds..." % i, attr)
				leftscr.refresh()
				gevent.sleep(1)
			leftscr.addstr("\nERROR\nYou do not have security permissions\n to perform this action.", attr)
			leftscr.refresh()
开发者ID:ekimekim,项目名称:hacking-game,代码行数:88,代码来源:main.py

示例12: DebugService

class DebugService(RpcService):
    def __init__(self, gevent=False, builtins=None):
        self.gevent = gevent
        self.backdoor_locals = builtins or {}
        self.backdoor_server = None

    @private
    def attach(self, host, port):
        import pydevd
        pydevd.settrace(host, port=port, stdoutToServer=True, stderrToServer=True)

    @private
    def detach(self):
        import pydevd
        pydevd.stoptrace()

    @private
    def dump_stacks(self):
        if self.gevent:
            from greenlet import greenlet

            # If greenlet is present, let's dump each greenlet stack
            dump = []
            for ob in gc.get_objects():
                if not isinstance(ob, greenlet):
                    continue
                if not ob:
                    continue   # not running anymore or not started

                dump.append(''.join(traceback.format_stack(ob.gr_frame)))

            return dump
        else:
            dump = []
            for frame in list(sys._current_frames().values()):
                dump.append(''.join(traceback.format_stack(frame)))

            return dump

    @private
    def start_backdoor(self):
        if not self.gevent:
            raise RpcException(errno.ENOTSUP, 'Not supported')

        from gevent import spawn
        from gevent.backdoor import BackdoorServer
        self.backdoor_server = BackdoorServer(
            ('127.0.0.1', 9999),
            banner='DebugService backdoor server',
            locals=self.backdoor_locals
        )

        spawn(self.backdoor_server.serve_forever())

    @private
    def stop_backdoor(self):
        if not self.gevent:
            raise RpcException(errno.ENOTSUP, 'Not supported')

        if self.backdoor_server:
            self.backdoor_server.close()
            self.backdoor_server = None
开发者ID:650elx,项目名称:middleware,代码行数:62,代码来源:debug.py

示例13: Server

class Server(object):
    """
    The emulation server

    Handles a set of devices
    """

    def __init__(self, name='', devices=(), backdoor=None):
        self.name = name
        self._log = logging.getLogger('{0}.{1}'.format(_log.name, name))
        self._log.info('Bootstraping server')
        if backdoor:
            from gevent.backdoor import BackdoorServer
            banner = 'Welcome to Bliss emulator server console.\n' \
                     'My name is {0!r}. You can access me through the ' \
                     '\'server()\' function. Have fun!'.format(name)
            self.backdoor = BackdoorServer(backdoor, banner=banner,
                                           locals=dict(server=weakref.ref(self)))
            self.backdoor.start()
            self._log.info('Backdoor opened at %r', backdoor)

        else:
            self._log.info('no backdoor declared')

        self.devices = {}
        for device in devices:
            try:
                self.create_device(device)
            except Exception as error:
                dname = device.get('name', device.get('class', 'unknown'))
                self._log.error('error creating device %s (will not be available): %s',
                                dname, error)
                self._log.debug('details: %s', error, exc_info=1)

    def terminate(self):
        for device in self.devices:
            for tp in device.transports:
                tp.terminate()

    def create_device(self, device_info):
        klass_name = device_info.get('class')
        name = device_info.get('name', klass_name)
        self._log.info('Creating device %s (%r)', name, klass_name)
        device, transports = create_device(device_info)
        self.devices[device] = transports
        return device, transports

    def get_device_by_name(self, name):
        for device in self.devices:
            if device.name == name:
                return device

    def start(self):
        for device in self.devices:
            for interface in self.devices[device]:
                interface.start()

    def stop(self):
        for device in self.devices:
            for interface in self.devices[device]:
                interface.stop()

    def serve_forever(self):
        stop_events = []
        for device in self.devices:
            for interface in self.devices[device]:
                stop_events.append(interface._stop_event)
        self.start()
        try:
            gevent.joinall(stop_events)
        finally:
            self.stop()

    def __str__(self):
        return '{0}({1})'.format(self.__class__.__name__, self.name)
开发者ID:tiagocoutinho,项目名称:bliss,代码行数:75,代码来源:emulator.py

示例14: Dissonance

class Dissonance(object):
    _name = None
    _web = None
    _manhole = None

    def __init__(self, config):
        opts_for = lambda name: EnvFallbackDict(name, getattr(config, '%s_opts' % name, {}))

        self._opts = EnvFallbackDict(None, getattr(config, 'dissonance_opts', {}))
        storage_class = get_storage_by_name(self._opts.get('storage', getattr(config, 'storage', 'shelve')))

        self.config = config
        self.client = Client()

        self._storage = storage_class(self, opts_for('storage'))
        self.modules = Modules(self)
        self._storage_sync_periodic = Periodic(int(self._opts.get('storage_sync_interval', 600)),
                                               self.modules._save_loaded_module_data)
        self._stop_event = Event()
        self._stop_event.set()

        self.client.events.on('message-create', self._handle_message)

    def _handle_message(self, message, client):
        if message.author == client.me:
            return

        # Schedule the handling of the message to occur during the next iteration of the event loop.
        gevent.spawn_raw(self.__handle_message, message)

    def __handle_message(self, message):
        logger.debug("Incoming message %r", message)
        start = time.time()

        message._dissonance = self
        message.targeting_client = message.content.startswith('doot, ')
        self.modules._handle_message(message)
        end = time.time()

        logger.debug("Took %.5f seconds to handle message %r", end - start, message)

    def _get_module_data(self, module):
        logger.debug("Getting module data for module %s", module.name)
        return self._storage.get_data_for_module_name(module.name)

    @property
    def name(self):
        return self.client.me.username

    @property
    def running(self):
        return not self._stop_event.is_set()

    @property
    def stopped(self):
        return not self.running

    @property
    def version(self):
        return version

    def run(self, auto_join=False):
        """
            Runs Dissonance, loading all the modules, starting the web service, and starting the adapter.

            If auto_join=True, this function will not return, and will run until dissonance stops if starting dissonance from
            outside of a greenlet.

        """
        if self.running:
            raise RuntimeError("Dissonance is already running!")

        logger.info("Starting Dissonance v%s", self.version)

        logger.info("Starting storage %s", self._storage)
        self._storage.start()

        logger.info("Loading modules")
        self.modules.load_all()

        if getattr(self.config, 'web', False) or str(self._opts.get('web', False)).upper() == 'TRUE':
            self._web = Web(self, EnvFallbackDict('web', getattr(self.config, 'web_opts', {})))
            self._web.start()

        if getattr(self.config, 'manhole', False):
            from gevent.backdoor import BackdoorServer
            manhole_opts = EnvFallbackDict('manhole', getattr(self.config, 'manhole_opts', {}))
            self._manhole = BackdoorServer((
                manhole_opts.get('listen_host', '127.0.0.1'),
                int(manhole_opts.get('listen_port', 9001))
            ), locals={
                'client': self.client
            })

            self._manhole.start()

        logger.info("Attempting to log in as %s" % self._opts['email'])
        self.client.login(self._opts['email'], self._opts['password'])
        logger.info("Starting connection to Discord")
        self.client.start()
#.........这里部分代码省略.........
开发者ID:jhgg,项目名称:dissonance,代码行数:101,代码来源:dissonance.py

示例15: main

def main(json_helper = _JSON_HELPER):
    """main event loop"""
    # catch redis errors and keyboard interrupts
    logging.info('Worker started')
    if BACKDOOR_PORT:
        backdoor = BackdoorServer(('127.0.0.1', BACKDOOR_PORT),
                dict(globals()))
        logging.info('Backdoor server at 127.0.0.1:%d', BACKDOOR_PORT)
        backdoor.start()
    try:
        REDIS.sadd(WORKER_LIST, _PID)
        # main loop
        worker_pool = gevent.pool.Pool(WORKER_THREADS)
        while True:
            # if we're no longer welcome, break out of the main loop
            if not REDIS.sismember(WORKER_LIST, _PID):
                logging.info(
                    'Worker PID released, waiting for threads, then exiting.')
                for thread in _THREADS:
                    thread.join()
                break

            # clean up completed tasks
            for thread in _THREADS:
                if thread.ready():
                    _THREADS.remove(thread)
                    WORKER_STATS.gthreads -= 1
                    logging.debug('GC: %s', thread)

            # yield for outstanding threads
            gevent.sleep()

            # grab the next request from the worker queue, or wait
            request = REDIS.blpop(WORKER_QUEUE, 5)
            if not request:
                # timeout waiting for request, lets us run the loop
                # again and check if we should still be here
                continue

            # request should be JSON
            try:
                request = json.loads(request[1])
            except ValueError:
                logging.error('Invalid JSON for request: %s', request[1])
                continue
            WORKER_STATS.requests.inc()

            # request should be a dict and have a request key with list val
            if (type(request) is not dict or
                    not request.has_key('method') or
                    type(request['method']) not in [unicode, str]):
                logging.error('Missing or invalid method: %s', request)
                continue
            method = request['method']

            # decode the arguments
            args = request.get('args', [])
            kwargs = request.get('kwargs', {})
            reply_to = request.get('reply_channel', None)
            no_exec = request.get('no_exec', None)

            # attempt to resolve the requested function
            # keeping a cache of them along the way
            if _EXEC_CACHE.has_key(method):
                executable = _EXEC_CACHE[method]
            else:
                executable = route_to_class_or_function(
                    method)
                _EXEC_CACHE[method] = executable
            if not executable:
                logging.error('Failed to find class or function at %s',
                    method)
                if reply_to:
                    REDIS.rpush(reply_to, json.dumps({
                        'message' : \
                            'Failed to find class or function at %s' % (
                                method),
                        'response_code' : 404,
                        'error' : True}))
                continue

            # instantiate if we're dealing with a class
            if type(executable) is type:
                if issubclass(executable, prototype.Cacheable):
                    # inherits cacheable, we only need one
                    if not _INST_CACHE.has_key(method):
                        # we don't have one yet, so make one
                        _INST_CACHE[method] = executable()
                        logging.debug('New cacheable instance: %s',
                                _INST_CACHE[method])
                    instance = _INST_CACHE[method]
                else:
                    # instantiate a regular class every call
                    instance = executable()
                    logging.debug('New instance: %s', instance)
                # get the instance method we care about
                if hasattr(instance, method.split('.')[-1]):
                    func = getattr(instance, method.split('.')[-1])
                else:
                    logging.error('Failed to find class or function at %s',
#.........这里部分代码省略.........
开发者ID:stevenewey,项目名称:bluecollar,代码行数:101,代码来源:worker.py


注:本文中的gevent.backdoor.BackdoorServer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。