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


Python BackdoorServer.start方法代码示例

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

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

示例1: startbackdoor

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
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,代码行数:11,代码来源:app.py


示例2: BackdoorPlugin

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
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,代码行数:17,代码来源:backdoor.py


示例3: Service

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]

#.........这里部分代码省略.........
    def add_timeout(self, func, plus, seconds, immediately=False):
        """Register a function to be called repeatedly.

        func (function): the function to call.
        plus (object): additional data to pass to the function.
        seconds (float): the minimum interval between successive calls
            (may be larger if a call doesn't return on time).
        immediately (bool): whether to call right off or wait also
            before the first call.

        """
        if plus is None:
            plus = {}
        func = functools.partial(func, **plus)
        if immediately:
            gevent.spawn(repeater, func, seconds)
        else:
            gevent.spawn_later(seconds, repeater, func, seconds)

    def exit(self):
        """Terminate the service at the next step.

        """
        logger.warning("%r received request to shut down.", self._my_coord)
        self.rpc_server.stop()

    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()
开发者ID:Karl-Krauth,项目名称:cms,代码行数:70,代码来源:service.py


示例4: setup_logging

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
                         match.group(1))
                self.msg(user.nick, "Try: \"Does napping make you smarter?\"")
        else:
            self.msg(user.nick, "Can't understand your command: \"%s\"" %
                     message)


if __name__ == '__main__':
    from girclib.helpers import setup_logging
    setup_logging(level=5)
    client = YahooAnswerBot('irc.freenode.net', 6667, 'girclib', 'gIRClib')

    # Just for the fun, start telnet backdoor on port 2000
    from gevent.backdoor import BackdoorServer
    server = BackdoorServer(('127.0.0.1', 2000), locals=locals())
    server.start()

    @signals.on_signed_on.connect
    def _on_motd(emitter):
        log.info("Signed on. Let's join #ufs")
        client.join("#ufs")

    @signals.on_disconnected.connect
    def disconnected(emitter):
        log.info("Exited!?")
        try:
            gevent.shutdown()
        except AssertionError:
            # Shutting down is only possible from MAIN greenlet
            pass
开发者ID:NorthIsUp,项目名称:gIRClib,代码行数:32,代码来源:yahoo.py


示例5: Service

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]

#.........这里部分代码省略.........
        func (function): the function to call.
        plus (object): additional data to pass to the function.
        seconds (float): the function will be called every seconds
                         seconds.
        immediately (bool): if True, func will be called also at the
                            beginning.

        """
        next_timeout = monotonic_time()
        if not immediately:
            next_timeout += seconds
        heapq.heappush(self._timeouts, (next_timeout, seconds, func, plus))

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

    def exit(self):
        """Terminate the service at the next step.

        """
        logger.warning("%s %d received request to shut down" % self._my_coord)
        self._exit = True

        # 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()
开发者ID:yunmanger1,项目名称:cms,代码行数:70,代码来源:GeventLibrary.py


示例6: BackdoorServer

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
import gevent.monkey
from gevent.wsgi import WSGIServer
from gevent.backdoor import BackdoorServer
from webservice import app
from ircservice import irc

gevent.monkey.patch_all()

backdoor = BackdoorServer(('127.0.0.1',18080))
backdoor.start()

irc.init()

http_server = WSGIServer(('', 8000), app)
http_server.serve_forever()
开发者ID:noricube,项目名称:efgd-bot,代码行数:17,代码来源:run.py


示例7: Server

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
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,代码行数:77,代码来源:emulator.py


示例8: Dissonance

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
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,代码行数:103,代码来源:dissonance.py


示例9: main

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
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,代码行数:103,代码来源:worker.py


示例10: main

# 需要导入模块: from gevent.backdoor import BackdoorServer [as 别名]
# 或者: from gevent.backdoor.BackdoorServer import start [as 别名]
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,代码行数:90,代码来源:main.py



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