• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python reactor.listenSSL函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: start

def start(config):
    """Start twisted event loop and the fun should begin..."""

    host = config.get('broker', 'host') 
    port = int(config.get('broker', 'port'))

    username = config.get('broker', 'username')
    password = config.get('broker', 'password')

    fileServerPort      = int(config.get('fileserver', 'port'))
    fileServerDirectory = config.get('fileserver', 'directory')

    # Start File Server
    try:
        privkey = os.path.abspath( os.path.dirname(__file__) + '/services/privkey.pem')
        cacert = os.path.abspath( os.path.dirname(__file__) + '/services/cacert.pem')
        logger.info('Using SSL, privkey = %s, cacert = %s' % (privkey, cacert))

        reactor.listenSSL(fileServerPort, FileServerFactory(fileServerDirectory), 
            ssl.DefaultOpenSSLContextFactory(privkey, cacert) )

        logger.info('Listening on port %d, serving files from directory: %s' % (fileServerPort, fileServerDirectory))
    except:
        logger.fatal("Unable to start file server at port: %d, please check." % fileServerPort)

    stompProtocolFactory = StompProtocolFactory()

    reactor.connectTCP(host, port, stompProtocolFactory)
    reactor.run()
    return internet.TCPClient(host, port, stompProtocolFactory)
开发者ID:phuonghoangtaisinh,项目名称:vmcontroller.unstable,代码行数:30,代码来源:__main__.py


示例2: Start

def Start():
	Globals.serverIP = "192.168.1.40"
	
	#MySQL Data
	Globals.dbHost = "127.0.0.1"
	Globals.dbUser = "user"
	Globals.dbPass = "pass"
	Globals.dbDatabase = "db"
	
	CheckMySqlConn()
	
	SSLInfo = ssl.DefaultOpenSSLContextFactory('crt/privkey.pem', 'crt/cacert.pem')
	
	factory = Factory()
	factory.protocol = GosRedirector.GOSRedirector
	reactor.listenSSL(42127, factory, SSLInfo)
	print("[SSL REACTOR] GOSREDIRECTOR STARTED [42127]")
	
	factory = Factory()
	factory.protocol = BlazeMain_Client.BLAZEHUB
	reactor.listenTCP(10041, factory)
	print("[TCP REACTOR] BLAZE CLIENT [10041]")
	
	factory = Factory()
	factory.protocol = BlazeMain_Server.BLAZEHUB
	reactor.listenTCP(10071, factory)
	print("[TCP REACTOR] BLAZE SERVER [10071]")
	
	sites = server.Site(Https.Simple())
	reactor.listenSSL(443, sites, SSLInfo)
	print("[WEB REACTOR] Https [443]")

	reactor.run()
开发者ID:buchacho,项目名称:BF4BlazeEmulator,代码行数:33,代码来源:Init.py


示例3: process_nmap_commands

def process_nmap_commands(logger_name):
	""" Main function. Here we set up the environment, factory and port """
	global nmap_commands_file
	global nmap_command
	global port
	global mlog
	global verbose_level
	global client_timeout

	observer = log.PythonLoggingObserver(logger_name)
	observer.start()

	# Create the factory
	factory = Factory()
	factory.protocol = NmapServerProtocol

	# Create the time based print
	loop = task.LoopingCall(show_info)
	loop.start(5) 

	# Create the time based file read
	loop2 = task.LoopingCall(read_file_and_fill_nmap_variable)
	loop2.start(1)

	# To mark idel clients as hold
	loop3 = task.LoopingCall(timeout_idle_clients)
	loop3.start(client_timeout) # call every second

	if not sql_file =="":
		loop4 = task.LoopingCall(sql_import_loop)
		loop4.start(5)

	# Create the reactor
	reactor.listenSSL(port, factory, ServerContextFactory())
	reactor.run()
开发者ID:PHPPlay,项目名称:Minions,代码行数:35,代码来源:dnmap_server.py


示例4: main

def main():
    logging.basicConfig(level=logging.INFO,
            format='%(asctime)s %(levelname)-s: %(message)s')
    args = _getArgs()

    ippool = IPPool(args.remote)
    ippool.register(args.local)

    factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config,
            local=args.local, remotePool=ippool)

    if args.no_ssl:
        logging.info('Running without SSL.')
        reactor.listenTCP(args.listen_port, factory)
    else:
        certificate = _load_cert(args.pem_cert)
        if certificate is None:
            logging.critical('Cannot read certificate.')
            sys.exit(2)
            return
        reactor.listenSSL(args.listen_port, factory,
                certificate.options(), interface=args.listen)

    logging.info('Listening on %s:%s...' % (args.listen, args.listen_port))
    reactor.run()
开发者ID:colabambino,项目名称:sstp-server,代码行数:25,代码来源:__init__.py


示例5: startagent

def startagent(port = myport):
	if agentdaemonize:
		print "Daemonizing"
		from hqdaemon import daemonize
		daemonize('/dev/null','/tmp/daemon.log','/tmp/daemon.log')
	if sys.platform.find("win32") != -1:
		import win32file
		win32file._setmaxstdio(2048)

	if use_ssl:
		print "Agent is started on port ", myport, " SSL is enabled "
		try:
			myContextFactory = ssl.DefaultOpenSSLContextFactory(agent_ssl_key, agent_ssl_cert)
			ctx = myContextFactory.getContext()
			# ctx.set_verify( SSL.VERIFY_PEER, verifyCallback)
			# ctx.set_options( SSL.OP_ALL ) 
			# Since we have self-signed certs we have to explicitly
			# tell the server to trust them.
			ctx.load_verify_locations(agent_ssl_pem)
		except Exception, e:
			print "Failed to start, SSL keys are specified but do not exist ", e
			sys.exit(1)
		
		reactor.listenSSL(myport, ExecuteActionFactory(), myContextFactory)
		reactor.run(installSignalHandlers=False)
开发者ID:stutiredboy,项目名称:HQ-Scheduler,代码行数:25,代码来源:hqagent.py


示例6: build_reactor

def build_reactor(options, **kwargs):
    web_socket_instance = FilteredWebSocketFactory(**kwargs)
    subscriber = kwargs.pop("subscriber", None)

    if options.key and options.cert:
        with open(options.key) as keyFile:
            with open(options.cert) as certFile:
                cert = ssl.PrivateCertificate.loadPEM(keyFile.read() + certFile.read())
                reactor.listenSSL(options.port, web_socket_instance, cert.options())
    else:
        reactor.listenTCP(
            options.port,
            web_socket_instance
        )
    if subscriber is not None:
        reactor.callInThread(
            subscriber.listener,
            web_socket_instance
        )
        reactor.addSystemEventTrigger(
            "before",
            "shutdown",
            subscriber.kill
        )

    # Start the consumer loop
    consumer_loop = LoopingCall(
        web_socket_instance.consumer
    )
    consumer_loop.start(0.001, now=False)
    return web_socket_instance
开发者ID:EricSchles,项目名称:filtered_websocket,代码行数:31,代码来源:server.py


示例7: main

def main():
    args = _getArgs()
    logging.basicConfig(level=args.log_level,
            format='%(asctime)s %(levelname)-s: %(message)s')
    logging.addLevelName(5, 'VERBOSE')

    ippool = IPPool(args.remote)
    ippool.register(args.local)

    if args.no_ssl:
        logging.info('Running without SSL.')
        factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config,
                local=args.local, remotePool=ippool, certHash=None)
        reactor.listenTCP(args.listen_port, factory)
    else:
        cert = _load_cert(args.pem_cert)
        sha1 = cert.digest('sha1').replace(':', '').decode('hex')
        sha256 = cert.digest('sha256').replace(':', '').decode('hex')
        cert_options = cert.options()

        if args.ciphers:
            cert_options.getContext().set_cipher_list(args.ciphers)

        factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config,
                local=args.local, remotePool=ippool, certHash=[sha1, sha256])
        reactor.listenSSL(args.listen_port, factory,
                cert_options, interface=args.listen)


    logging.info('Listening on %s:%s...' % (args.listen, args.listen_port))
    reactor.run()
开发者ID:deba12,项目名称:sstp-server,代码行数:31,代码来源:__init__.py


示例8: main

def main():
    """This runs the protocol on port 25000"""
    factory = protocol.Factory()
    factory.protocol = Echo
    reactor.listenSSL(25000, factory,
                      ssl.DefaultOpenSSLContextFactory(KEYFILE, CERTFILE))
    reactor.run()
开发者ID:GMLudo,项目名称:curio,代码行数:7,代码来源:twistsslecho.py


示例9: main

def main():
    """ Run the server. """
    # setup logger first
    initLog()

    # Load the client's self-signed certificate.
    clientCert = open(CLIENT_CERT_FILE).read()
    clientCertObj = ssl.Certificate.loadPEM(clientCert)

    # Load the server's key and the server's self-signed certificate.
    serverKey = open(SERVER_KEY_FILE).read()
    serverCert = open(SERVER_CERT_FILE).read()
    serverPEM = serverKey + serverCert
    serverCertObj = ssl.PrivateCertificate.loadPEM(serverPEM)

    # Create an SSL context factory. Passing the client's certificate along enables client authentication.
    sslContextFactory = serverCertObj.options(clientCertObj)

    kinectServerFactory = KinectServerFactory()

    # Set the Twisted reactor up to listen for connections. For each incoming connection, create a KinectServer
    # (using the KinectServerFactory) and create an SSL context (using the sslContextFactory). The SSL context is used
    # to verify clients and set up an SSL layer. The KinectServer is used to handle all messages their decrypted state;
    # messages are relayed to all other connections.
    reactor.listenSSL(PORT, kinectServerFactory, sslContextFactory)

    # Run the reactor (which enters Twisted's main loop).
    reactor.run()
开发者ID:zad,项目名称:KinectMonitor,代码行数:28,代码来源:kinectserver.py


示例10: main

def main(argv):
    (logLevel, sslPort, httpPort,
     certFile, keyFile, userName,
     groupName, background,
     incomingInterface)     = parseOptions(argv)
    privateKey              = initializeKey(keyFile)
    database                = initializeDatabase()
    sslFactory              = initializeFactory(database, privateKey)
    connectFactory          = http.HTTPFactory(timeout=10)
    connectFactory.protocol = ConnectChannel
    
    reactor.listenSSL(sslPort, sslFactory, ServerContextFactory(certFile, keyFile),
                      interface=incomingInterface)
    reactor.listenSSL(4242, sslFactory, ServerContextFactory(certFile, keyFile),
                      interface=incomingInterface)
    reactor.listenTCP(port=httpPort, factory=connectFactory,
                      interface=incomingInterface)
        
    initializeLogging(logLevel)
    checkPrivileges(userName, groupName)

    if background:
        print "\nconvergence " + str(gVersion) + " by Moxie Marlinspike backgrounding..."
        convergence.daemonize.createDaemon()
    else:
        print "\nconvergence " + str(gVersion) + " by Moxie Marlinspike running..."

    writePidFile()
    dropPrivileges(userName, groupName)

    reactor.run()
开发者ID:Telarian,项目名称:Convergence,代码行数:31,代码来源:convergence-notary.py


示例11: runApplication

def runApplication():
    opts = Options()
    opts.parseOptions()

    common.initLogs(opts['logfile'])

    common.installReactor(opts['reactor'])

    config = common.loadConfig(opts['config'])

    #starting services with options from config
    if opts['ssl']:
        reactor.listenSSL(
            config.getint('finger', 'port'),
            FingerFactory(),
            DefaultOpenSSLContextFactory(
                config.get('ssl', 'cert'),
                config.get('ssl', 'private')
            )
        )
        reactor.listenSSL(
            config.getint('web', 'port'),
            server.Site(SomeLeafResource()),
            DefaultOpenSSLContextFactory(
                config.get('ssl', 'cert'),
                config.get('ssl', 'private')
            )
        )
    else:
        reactor.listenTCP(config.getint('finger', 'port'), FingerFactory())
        reactor.listenTCP(config.getint('web', 'port'), server.Site(SomeLeafResource()))
    reactor.run()
开发者ID:lorehov,项目名称:tx-deploy-templates,代码行数:32,代码来源:server.py


示例12: main

def main():

    parser = OptionParser()
    parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
    parser.add_option('-p', '--port', default=4443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
    parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
    (options, _) = parser.parse_args()
    
    x = logging.getLogger()
    x.setLevel(log_levels[options.logLevel])
    
    if options.logfile != None:
        h = logging.FileHandler(options.logfile)
    else:
        h = logging.StreamHandler()
    
    f = logging.Formatter(u"%(levelname)s %(message)s")
    h.setFormatter(f)
    x.addHandler(h)
    
    
    x.info("Starting server on port {0}".format(options.port))
    reactor.listenSSL(options.port, SiriFactory(), ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt'))
    reactor.run()
    x.info("Server shutdown complete")
开发者ID:413x,项目名称:SiriServerCore,代码行数:25,代码来源:SiriServer.py


示例13: start_listening

    def start_listening(self):
        config = self.get_config()

        if not config.no_tls and config.bind_port is not None:
            reactor.listenSSL(
                config.bind_port,
                Site(self.root_resource),
                self.tls_context_factory,
                interface=config.bind_host
            )
            logger.info("Synapse now listening on port %d", config.bind_port)

        if config.unsecure_port is not None:
            reactor.listenTCP(
                config.unsecure_port,
                Site(self.root_resource),
                interface=config.bind_host
            )
            logger.info("Synapse now listening on port %d", config.unsecure_port)

        metrics_resource = self.get_resource_for_metrics()
        if metrics_resource and config.metrics_port is not None:
            reactor.listenTCP(
                config.metrics_port, Site(metrics_resource), interface="127.0.0.1",
            )
            logger.info("Metrics now running on 127.0.0.1 port %d", config.metrics_port)
开发者ID:cryptoempathy,项目名称:synapse,代码行数:26,代码来源:homeserver.py


示例14: main

def main(argv):
    FLAGS(argv)
    if not FLAGS.logfile and not FLAGS.daemonize:
        # No log file and not daemonized.
        log.startLogging(sys.stderr)
    elif not FLAGS.logfile and FLAGS.daemonize:
        # Daemonized, but no log file.
        fd, name = tempfile.mkstemp(prefix='flamongo', suffix='.log')
        os.close(fd)
        sys.stderr.write('Logging to %s\n' % name)
        log.startLogging(open(name, 'a'))
    else:
        f = open(FLAGS.logfile, 'a')
        log.startLogging(f)
    # FIXME
    mongoengine.connect('flamongo')
    # TODO define connection options.
    site = server.Site(TopLevel(lambda: Connection()))
    reactor.listenTCP(FLAGS.port, site)
    try:
        from twisted.internet import ssl
        ssl_context = ssl.DefaultOpenSSLContextFactory(FLAGS.privatekey,
            FLAGS.certificate)
        reactor.listenSSL(FLAGS.secureport, site, ssl_context)
    except ImportError:
        # removes the partial import.
        ssl = None
        log.err('SSL not enabled. Needs PyOpenSSL.')
    except Exception as ex:
        log.err(str(ex))
    if FLAGS.daemonize:
        utils.daemonize()
    reactor.run()
开发者ID:crew,项目名称:metrics-backend,代码行数:33,代码来源:main.py


示例15: process_nmap_commands

def process_nmap_commands(loggerName):
    """ Main function. Here we set up the environment, factory, interface, and port """
    global nmapCommandsFile
    global nmapCommand
    global port
    global mlog
    global verboseLevel
    global clientTimeout
    
    observer = log.PythonLoggingObserver(loggerName)
    observer.start()
    
    # Create the factory
    factory = Factory()
    factory.protocol = NmapServerProtocol
    
    # Create the time based print
    loop = task.LoopingCall(show_info)
    loop.start(5.0) # call every second
    
    # Create the time based file read
    loop2 = task.LoopingCall(read_file_and_fill_nmap_variable)
    loop2.start(30.0) # call every second
    
    # To mark idle clients as hold
    loop3 = task.LoopingCall(timeout_idle_clients)
    loop3.start(clientTimeout) # call every second
    
    # Create the reactor
    reactor.listenSSL(port, factory, ServerContextFactory(), interface=interface)
    reactor.run()
开发者ID:theRhinoLogician,项目名称:dnmapR,代码行数:31,代码来源:dnmapR_server.py


示例16: addWebServer

def addWebServer(cfg, dist, sched):
    """Set up a web server.
         cfg -- a configuration object from Main.  We use these options:
                HTTPS_N_BRIDGES_PER_ANSWER
                HTTP_UNENCRYPTED_PORT
                HTTP_UNENCRYPTED_BIND_IP
                HTTP_USE_IP_FROM_FORWARDED_HEADER
                HTTPS_PORT
                HTTPS_BIND_IP
                HTTPS_USE_IP_FROM_FORWARDED_HEADER
         dist -- an IPBasedDistributor object.
         sched -- an IntervalSchedule object.
    """
    Site = twisted.web.server.Site
    site = None
    if cfg.HTTP_UNENCRYPTED_PORT:
        ip = cfg.HTTP_UNENCRYPTED_BIND_IP or ""
        resource = WebResource(dist, sched, cfg.HTTPS_N_BRIDGES_PER_ANSWER,
                       cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER,
                       includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS)
        site = Site(resource)
        reactor.listenTCP(cfg.HTTP_UNENCRYPTED_PORT, site, interface=ip)
    if cfg.HTTPS_PORT:
        from twisted.internet.ssl import DefaultOpenSSLContextFactory
        #from OpenSSL.SSL import SSLv3_METHOD
        ip = cfg.HTTPS_BIND_IP or ""
        factory = DefaultOpenSSLContextFactory(cfg.HTTPS_KEY_FILE,
                                               cfg.HTTPS_CERT_FILE)
        resource = WebResource(dist, sched, cfg.HTTPS_N_BRIDGES_PER_ANSWER,
                       cfg.HTTPS_USE_IP_FROM_FORWARDED_HEADER,
                       includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS)
        site = Site(resource)
        reactor.listenSSL(cfg.HTTPS_PORT, site, factory, interface=ip)
    return site
开发者ID:katmagic,项目名称:BridgeDB,代码行数:34,代码来源:Server.py


示例17: start_site

def start_site(config, resource):
    log.info('Starting the API on port %s' % config.port)
    if config.sslkey and config.sslcert:
        reactor.listenSSL(config.port, PixelatedSite(resource), _ssl_options(config.sslkey, config.sslcert),
                          interface=config.host)
    else:
        reactor.listenTCP(config.port, PixelatedSite(resource), interface=config.host)
开发者ID:carriercomm,项目名称:pixelated-user-agent,代码行数:7,代码来源:application.py


示例18: __init__

    def __init__(
        self,
        port,
        ssl,
        server_context_factory = None,
        reactor = None,
        interface = '',
        **keywords
    ):

        if reactor is None:
            from twisted.internet import reactor

        if ssl and server_context_factory is None:
            from planes.sh.ssl import ServerContextFactory
            server_context_factory = ServerContextFactory()

        self.port = port
        self.ssl = ssl
        self.reactor = reactor
        self.factory = self.Factory(reactor = reactor, **keywords)

        if ssl:
            reactor.listenSSL(
                self.port,
                self.factory,
                server_context_factory,
                interface = interface,
            )
        else:
            reactor.listenTCP(
                port,
                self.factory,
                interface = interface,
            )
开发者ID:kriskowal,项目名称:planes,代码行数:35,代码来源:application.py


示例19: Run

def Run(withListen=True):

    global instance_SBProtocolFactory, bReactorStopped
    instance_SBProtocolFactory = SBProtocolFactory()

    InternalMessage.protocolInternal = SBProtocol()
    InternalMessage.protocolInternal.role = "internal"
    InternalMessage.protocolInternal.factory = instance_SBProtocolFactory
    threading.Thread(target=InternalMessage.Run).start()

    if withListen:
        reactor.listenTCP(9630, instance_SBProtocolFactory)  # @UndefinedVariable

        cert = None
        with open("server.pem") as keyAndCert:
            cert = ssl.PrivateCertificate.loadPEM(keyAndCert.read())
        reactor.listenSSL(9631, instance_SBProtocolFactory, cert.options())
        reactor.listenTCP(9632, EchoProtocolFactory())  # @UndefinedVariable

    try:
        reactor.run()  # @UndefinedVariable
    except:
        pass
    InternalMessage.Stop()
    bReactorStopped = True
    try:
        # reactor.stop()
        import sys

        sys.exit(0)
    except:
        pass
开发者ID:skycucumber,项目名称:Messaging-Gateway,代码行数:32,代码来源:ProtocolReactor.py


示例20: run

 def run(self):
     task.LoopingCall(self.status_check).start(0.5)
     root = File('www')
     root.putChild('st', StatusHandler(self))
     root.putChild('upd', self.updateHandler)
     root.putChild('cfg', ConfigHandler(self))
     root.putChild('upt', UptimeHandler(self))
     
     if self.config['config']['use_auth']:
         clk = ClickHandler(self)
         args={self.config['site']['username']:self.config['site']['password']}
         checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**args)
         realm = HttpPasswordRealm(clk)
         p = portal.Portal(realm, [checker])
         credentialFactory = BasicCredentialFactory("Garage Door Controller")
         protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])
         root.putChild('clk', protected_resource)
     else:
         root.putChild('clk', ClickHandler(self))
     
     site = server.Site(root)
     
     if not self.get_config_with_default(self.config['config'], 'use_https', False):
         reactor.listenTCP(self.config['site']['port'], site)  # @UndefinedVariable
         reactor.run()  # @UndefinedVariable
     else:
         sslContext = ssl.DefaultOpenSSLContextFactory(self.config['site']['ssl_key'], self.config['site']['ssl_cert'])
         reactor.listenSSL(self.config['site']['port_secure'], site, sslContext)  # @UndefinedVariable
         reactor.run()  # @UndefinedVariable
开发者ID:andrewshilliday,项目名称:garage-door-controller,代码行数:29,代码来源:controller.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python reactor.listenTCP函数代码示例发布时间:2022-05-27
下一篇:
Python reactor.listenMulticast函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap