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


Python Factory.protocol方法代码示例

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


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

示例1: Start

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
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,代码行数:35,代码来源:Init.py

示例2: start

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
    def start(self):
        # Start the zeroconf subsystem
        discover.init()
        
        # Setup the callback to shutdown
        signal.signal(signal.SIGINT, self.stop)

        # Create the listener
        reactor.listenTCP(8000, pb.PBServerFactory(Nearby()))

        # Listen for new hosts in the twisted thread
        f = Factory()
        f.protocol = Discovery
        reactor.listenTCP(8001, f)

        # Listen for new plugins
        f = Factory()
        f.protocol = NearbyLocal
        reactor.listenTCP(8002, f, interface="127.0.0.1")

        # Start up a web server to provide the software to other clients
        reactor.listenTCP(8003, server.Site(static.File('dist/')))

        # Advertise the node to the network
        reactor.callLater(.1, self.advertise)

        # Create a taskbar icon
        OsSpecific.TaskbarApplet(self.stop, self, outbound_nodes)

        # Start Twisted
        reactor.run()
开发者ID:mcolyer,项目名称:nearby,代码行数:33,代码来源:framework.py

示例3: connect_agent_eachother

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
def connect_agent_eachother(server_id):
    """
    Agent进程调用,监听自己的端口,并与其他Agent建立连接
    """
    ftlog.debug('connect_agent_eachother', server_id)
    myconf = ftcon.server_map[server_id]
    myip = myconf['ip']
    agentids = ftcon.server_type_map.get('AG', None)
    for agentid in agentids:
        agent = ftcon.server_map.get(agentid, None)
        ip = agent['ip']
        inner_port = agent['protocols']['server']['a2s']
        outer_port = agent['protocols']['server']['a2a']
        if agentid == server_id:
            # listen inner port for inner process
            factory = Factory()
            factory.protocol = A2SProtocol
            reactor.listenTCP(inner_port, factory)
            ftlog.info('Agent Start, listen for services port', inner_port)
            # listen outer port for other agent
            factory = Factory()
            factory.protocol = A2AProtocol
            reactor.listenTCP(outer_port, factory)
            ftlog.info('Agent Start, listen for agent port', outer_port)
        else:
            # 只连接比自己的ID大的agent,这样节省一半的连接,n*(n-1)/2
            if cmp(agentid, server_id) > 0:
                factory = FTReconnectFactory()
                factory.protocol = A2AProtocol
                if ip == myip:
                    ip = '127.0.0.1'
                reactor.connectTCP(ip, outer_port, factory)
                ftlog.info('Agent connect Agent', agentid, server_id)
开发者ID:zhaozw,项目名称:hall37,代码行数:35,代码来源:wrapper.py

示例4: setUpp

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
 def setUpp(self):
     factory = Factory()
     factory.protocol = MyProtocolServerSide
     factory_c = Factory()
     factory_c.protocol = MyProtocolClientSide
     endpoint = TCP4ServerEndpoint(reactor, 8007)
     endpoint.listen(factory)
     point = TCP4ClientEndpoint(reactor, "localhost", 8007)
     d = point.connect(factory_c)
     d.addCallback(self.registerProtocol)
     return d
开发者ID:spherecoder,项目名称:sphericalRepo,代码行数:13,代码来源:test_test.py

示例5: _processRequest

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
    def _processRequest(self):
        """
        Process the request by sending it to the relevant server.

        @return: the HTTP response.
        @rtype: L{Response}
        """
        ssl, host, port, _ignore_path = self.server.details()
        path = "/" + config.Servers.ConduitName

        headers = Headers()
        headers.setHeader("Host", utf8String(host + ":{}".format(port)))
        if self.streamType:
            # For attachments we put the base64-encoded JSON data into a header
            headers.setHeader("Content-Type", self.streamType)
            headers.addRawHeader("XPOD", base64.b64encode(self.data))
        else:
            headers.setHeader("Content-Type", MimeType("application", "json", params={"charset": "utf-8", }))
        headers.setHeader("User-Agent", "CalendarServer/{}".format(version))
        headers.addRawHeader(*self.server.secretHeader())

        from twisted.internet import reactor
        f = Factory()
        f.protocol = HTTPClientProtocol
        ep = GAIEndpoint(reactor, host, port, _configuredClientContextFactory() if ssl else None)
        proto = (yield ep.connect(f))

        request = ClientRequest("POST", path, headers, self.stream if self.stream is not None else self.data)

        if accountingEnabledForCategory("xPod"):
            self.loggedRequest = yield self.logRequest(request)

        response = (yield proto.submitRequest(request))

        returnValue(response)
开发者ID:eventable,项目名称:CalendarServer,代码行数:37,代码来源:request.py

示例6: process_nmap_commands

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
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,代码行数:37,代码来源:dnmap_server.py

示例7: connect

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
def connect(sdata, command, username, host, port=22, key_file=None, password=None):
    """
    Connect to an SSH host (as it happens, persistently).
    """
    sdata.set_conn_state('connecting')

    try:
        keys = [Key.fromFile(key_file)] if key_file else None
    except exceptions.IOError as e:
        print('### key load error:', str(e))
        push_failure_message(str(e), sdata)
        return

    endpoint = SSHCommandClientEndpoint.newConnection(
                    reactor, command, username, host, port=int(port),
                    keys=keys, password=password, ui=None,
                    knownHosts=PermissiveKnownHosts())

    factory = Factory()
    factory.protocol = LineProtocol
    factory.sdata = sdata

    d = endpoint.connect(factory)

    # Very small race condition between here and the replacement
    # in connectionMade() above, but I've never managed to hit it.
    def disconnect():
        sdata.log('Disconnecting while still attempting to connect, by request')
        d.cancel()
    sdata.transport_drop_cb = disconnect

    d.addErrback(lambda reason: push_failure_message(reason, sdata))
    return d
开发者ID:cisco,项目名称:xr-telemetry-m2m-web,代码行数:35,代码来源:ssh.py

示例8: test_connectionCancelledBeforeSecure

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
    def test_connectionCancelledBeforeSecure(self):
        """
        If the connection is cancelled before the SSH transport layer has
        finished key exchange (ie, gotten to the point where we may attempt to
        authenticate), the L{Deferred} returned by
        L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
        L{CancelledError} and the connection is aborted.
        """
        endpoint = SSHCommandClientEndpoint.newConnection(
            self.reactor, b"/bin/ls -l", b"dummy user",
            self.hostname, self.port, knownHosts=self.knownHosts,
            ui=FixedResponseUI(False))

        factory = Factory()
        factory.protocol = Protocol
        d = endpoint.connect(factory)

        transport = AbortableFakeTransport(None, isServer=False)
        factory = self.reactor.tcpClients[0][2]
        client = factory.buildProtocol(None)
        client.makeConnection(transport)
        d.cancel()

        self.failureResultOf(d).trap(CancelledError)
        self.assertTrue(transport.aborted)
        # Make sure the connection closing doesn't result in unexpected
        # behavior when due to cancellation:
        client.connectionLost(Failure(ConnectionDone()))
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:30,代码来源:test_endpoints.py

示例9: _exitStatusTest

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
    def _exitStatusTest(self, request, requestArg):
        """
        Test handling of non-zero exit statuses or exit signals.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)
        connectionLost = []
        protocol.connectionLost = connectionLost.append

        # Figure out which channel on the connection this protocol is associated
        # with so the test can simulate command exit and channel close.
        channelId = protocol.transport.id
        channel = server.service.channels[channelId]

        server.service.sendRequest(channel, request, requestArg)
        channel.loseConnection()
        pump.pump()
        self.assertClientTransportState(client, False)
        return connectionLost[0]
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:29,代码来源:test_endpoints.py

示例10: test_dataReceived

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
    def test_dataReceived(self):
        """
        After establishing the connection, when the command on the SSH server
        produces output, it is delivered to the protocol's C{dataReceived}
        method.
        """
        self.realm.channelLookup[b'session'] = WorkingExecSession
        endpoint = self.create()

        factory = Factory()
        factory.protocol = Protocol
        connected = endpoint.connect(factory)

        server, client, pump = self.finishConnection()

        protocol = self.successResultOf(connected)
        dataReceived = []
        protocol.dataReceived = dataReceived.append

        # Figure out which channel on the connection this protocol is
        # associated with so the test can do a write on it.
        channelId = protocol.transport.id

        server.service.channels[channelId].write(b"hello, world")
        pump.pump()
        self.assertEqual(b"hello, world", b"".join(dataReceived))
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:28,代码来源:test_endpoints.py

示例11: create

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
    def create(self):
        """
        Create and return a new L{SSHCommandClientEndpoint} using the
        C{existingConnection} constructor.
        """
        factory = Factory()
        factory.protocol = Protocol
        connected = self.endpoint.connect(factory)

        # Please, let me in.  This kinda sucks.
        channelLookup = self.realm.channelLookup.copy()
        try:
            self.realm.channelLookup[b'session'] = WorkingExecSession

            server, client, pump = self.connectedServerAndClient(
                self.factory, self.reactor.tcpClients[0][2])

        finally:
            self.realm.channelLookup.clear()
            self.realm.channelLookup.update(channelLookup)

        self._server = server
        self._client = client
        self._pump = pump

        protocol = self.successResultOf(connected)
        connection = protocol.transport.conn
        return SSHCommandClientEndpoint.existingConnection(
            connection, b"/bin/ls -l")
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:31,代码来源:test_endpoints.py

示例12: start_AMP

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
 def start_AMP(self, p_pyhouse_obj):
     l_endpoint = TCP4ServerEndpoint
     l_factory = Factory()
     l_factory.protocol = AMP
     p_pyhouse_obj.Services.IrControlService = StreamServerEndpointService(l_endpoint, l_factory)
     p_pyhouse_obj.Services.IrControlService.setName('IrControl')
     p_pyhouse_obj.Services.IrControlService.setServiceParent(p_pyhouse_obj.Twisted.Application)
开发者ID:,项目名称:,代码行数:9,代码来源:

示例13: startSocketServer

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
def startSocketServer(root_node, shutdownOnLastDisconnect, interactive, socket=None, extra_loggers=None):
    """
    Bind the first available unix socket.
    Return the socket file.
    """
    # Create protocol factory.
    factory = Factory()
    factory.connectionPool = set()  # List of currently, active connections
    factory.protocol = CliClientProtocol
    factory.shutdownOnLastDisconnect = shutdownOnLastDisconnect
    factory.root_node = root_node
    factory.interactive = interactive
    factory.extra_loggers = extra_loggers or []
    factory.runtime_options = Options()

    # Listen on socket.
    if socket:
        reactor.listenUNIX(socket, factory)
    else:
        # Find a socket to listen on. (if no socket was given.)
        i = 0
        while True:
            try:
                socket = "/tmp/deployer.sock.%s.%i" % (getpass.getuser(), i)
                reactor.listenUNIX(socket, factory)
                break
            except CannotListenError:
                i += 1

                # When 100 times failed, cancel server
                if i == 100:
                    logging.warning("100 times failed to listen on posix socket. Please clean up old sockets.")
                    raise

    return socket
开发者ID:JeffreyVdb,项目名称:python-deployer,代码行数:37,代码来源:socket_server.py

示例14: sign

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
    def sign(self, challenge):
        if "SSH_AUTH_SOCK" not in os.environ:
            raise Exception("no ssh-agent is running!")

        factory = Factory()
        factory.noisy = False
        factory.protocol = SSHAgentClient
        endpoint = UNIXClientEndpoint(self._reactor, os.environ["SSH_AUTH_SOCK"])
        d = endpoint.connect(factory)

        @inlineCallbacks
        def on_connect(agent):
            # we are now connected to the locally running ssh-agent
            # that agent might be the openssh-agent, or eg on Ubuntu 14.04 by
            # default the gnome-keyring / ssh-askpass-gnome application
            blob = pack(['ssh-ed25519', self.public_key(binary=True)])

            # now ask the agent
            signature_blob = yield agent.signData(blob, challenge)
            algo, signature = unpack(signature_blob)

            agent.transport.loseConnection()

            returnValue(signature)

        return d.addCallback(on_connect)
开发者ID:markope,项目名称:AutobahnPython,代码行数:28,代码来源:cryptosign.py

示例15: main

# 需要导入模块: from twisted.internet.protocol import Factory [as 别名]
# 或者: from twisted.internet.protocol.Factory import protocol [as 别名]
def main(reactor):
    ep = SSHCommandClientEndpoint.newConnection(
        reactor, b'/bin/cat',
        details['USER'],
        details['HOST'],
        port=details['PORT'],
        password=details['PASSWORD'],
        agentEndpoint=None,
        knownHosts=None)
    factory = Factory()
    factory.protocol = MyProtocol

    d = ep.connect(factory)


    def gotConnection(proto):
        # stdio interface
        stdio_proto = StdinProto(proto.transport.conn)
        stdio.StandardIO(stdio_proto)

        # factory = Factory()
        # factory.protocol = MyProtocol

        # e = SSHCommandClientEndpoint.existingConnection(conn, b"/bin/echo hey")
        # return e.connect(factory).addCallback(lambda proto: proto.finished)
        return stdio_proto.finished

    return d.addCallback(gotConnection)
开发者ID:moldit,项目名称:mold,代码行数:30,代码来源:ssh2.py


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