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

Python protocol.Factory类代码示例

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

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



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

示例1: createProxyConnection

 def createProxyConnection(self, ip, port):
     factory = Factory()
     factory.protocol = Receiver
     point = TCP4ClientEndpoint(reactor, ip, port)
     d = point.connect(factory)
     d.addCallback(self.gotProxy)
     d.addErrback(self.cantConnect)
开发者ID:nixeagle,项目名称:pokemon-online-web,代码行数:7,代码来源:server.py


示例2: test_connectionCancelledBeforeSecure

    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,代码行数:28,代码来源:test_endpoints.py


示例3: test_publicKeyAuthenticationFailure

    def test_publicKeyAuthenticationFailure(self):
        """
        If the SSH server rejects the key pair presented during authentication,
        the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
        with a L{Failure} wrapping L{AuthenticationFailed}.
        """
        badKey = Key.fromString(privateRSA_openssh)
        self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})

        endpoint = SSHCommandClientEndpoint.newConnection(
            self.reactor, b"/bin/ls -l", self.user,
            self.hostname, self.port, keys=[badKey],
            knownHosts=self.knownHosts, ui=FixedResponseUI(False))

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

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

        f = self.failureResultOf(connected)
        f.trap(AuthenticationFailed)
        # XXX Should assert something specific about the arguments of the
        # exception

        # Nothing useful can be done with the connection at this point, so the
        # endpoint should close it.
        self.assertTrue(client.transport.disconnecting)
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:29,代码来源:test_endpoints.py


示例4: test_dataReceived

    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,代码行数:26,代码来源:test_endpoints.py


示例5: _exitStatusTest

    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,代码行数:27,代码来源:test_endpoints.py


示例6: start

 def start(self):
     factory = Factory()
     factory.protocol = WorkerProtocol
     factory.master = self
     self.reactor.listenTCP(8005, factory)
     
     self.launchClient()
开发者ID:adrianPerez,项目名称:twisted-server-cpp-worker,代码行数:7,代码来源:workerManager.py


示例7: create

    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,代码行数:29,代码来源:test_endpoints.py


示例8: connect

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,代码行数:33,代码来源:ssh.py


示例9: 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


示例10: main

def main(reactor, *argv):
    parameters = ConnectionParameters.fromCommandLine(reactor, argv)
    endpoint = parameters.endpointForCommand(b"/bin/cat")

    done = []
    factory = Factory()
    factory.protocol = Protocol
    d = endpoint.connect(factory)

    def gotConnection(proto):
        conn = proto.transport.conn

        for i in range(50):
            factory = Factory()
            factory.protocol = PrinterProtocol
            factory.done = Deferred()
            done.append(factory.done)

            e = SSHCommandClientEndpoint.existingConnection(
                conn, b"/bin/echo %d" % (i,))
            yield e.connect(factory)

    d.addCallback(gotConnection)
    d.addCallback(lambda work: cooperate(work).whenDone())
    d.addCallback(lambda ignored: gatherResults(done))

    return d
开发者ID:wellbehavedsoftware,项目名称:wbs-graphite,代码行数:27,代码来源:echoclient_shared_ssh.py


示例11: connect

 def connect():
     from twisted.internet.endpoints import TCP4ClientEndpoint
     from twisted.internet.protocol import Factory
     endpoint = TCP4ClientEndpoint(reactor, "127.0.0.1", 1235)
     factory = Factory()
     factory.protocol = Bot
     return endpoint.connect(factory)
开发者ID:DBrianKimmel,项目名称:amp-example,代码行数:7,代码来源:fake_slave.py


示例12: setUpClient

 def setUpClient(self):
     factory = Factory()
     factory.protocol = FileReceiver
     point = TCP4ClientEndpoint(reactor, "localhost", 8007)
     d = point.connect(factory)
     d.addCallback(self.registerProtocol)
     return  d
开发者ID:spherecoder,项目名称:sphericalRepo,代码行数:7,代码来源:TestFileButler.py


示例13: makeService

    def makeService(self, options):
        config.load_config(options['config_paths'])

        factory = Factory()
        factory.protocol = TacacsProtocol

        return internet.TCPServer(49, factory)
开发者ID:jcollie,项目名称:secant,代码行数:7,代码来源:secant_plugin.py


示例14: main

def main():
    config = ConfigParser.ConfigParser()
    config.read(os.path.expanduser('~/.b07'))
    api = b07.api.API(reactor,
                      config.get('ingress', 'email'),
                      config.get('ingress', 'password'))
    

    http_root = Redirect('https://localhost:{}/'.format(config.get('server', 'https_port')))
    http_factory = Site(http_root)
    http_endpoint = endpoints.serverFromString(reactor,
                                               'tcp:{}'.format(config.get('server', 'http_port')))
    http_endpoint.listen(http_factory)

    https_root = File(os.path.expanduser(config.get('server', 'web_root')))
    https_root.indexNames = ['index.html']
    https_factory = Site(https_root)
    https_endpoint = endpoints.serverFromString(reactor,
                                                'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'https_port'),
                                                                                         os.path.expanduser(config.get('server', 'ssl_key')),
                                                                                         os.path.expanduser(config.get('server', 'ssl_cert'))))
    https_endpoint.listen(https_factory)

    wsfactory = Factory()
    wsfactory.protocol = WebSocketProtocol
    wss_endpoint = endpoints.serverFromString(reactor,
                                              'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'wss_port'),
                                                                                       os.path.expanduser(config.get('server', 'ssl_key')),
                                                                                       os.path.expanduser(config.get('server', 'ssl_cert'))))
    wss_endpoint.listen(txws.WebSocketFactory(wsfactory))



    reactor.run()
开发者ID:drhinehart,项目名称:b07bot,代码行数:34,代码来源:server.py


示例15: 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


示例16: copyToStdout

def copyToStdout(endpoint):
    echoFactory = Factory()
    echoFactory.protocol = StdoutEcho
    echoFactory.finished = Deferred()
    d = endpoint.connect(echoFactory)
    d.addErrback(echoFactory.finished.errback)
    return echoFactory.finished
开发者ID:AlekSi,项目名称:twisted-benchmarks,代码行数:7,代码来源:sshendpoint.py


示例17: _processRequest

    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,代码行数:35,代码来源:request.py


示例18: main

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,代码行数:28,代码来源:ssh2.py


示例19: test_loseConnection

    def test_loseConnection(self):
        """
        The transport connected to the protocol has a C{loseConnection} method
        which causes the channel in which the command is running to close and
        the overall connection to be closed.
        """
        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)
        closed = self.record(server, protocol, 'closed', noArgs=True)
        protocol.transport.loseConnection()
        pump.pump()
        self.assertEqual([None], closed)

        # Let the last bit of network traffic flow.  This lets the server's
        # close acknowledgement through, at which point the client can close
        # the overall SSH connection.
        pump.pump()

        # Nothing useful can be done with the connection at this point, so the
        # endpoint should close it.
        self.assertTrue(client.transport.disconnecting)
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:29,代码来源:test_endpoints.py


示例20: sign

    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,代码行数:26,代码来源:cryptosign.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python protocol.Protocol类代码示例发布时间:2022-05-27
下一篇:
Python protocol.ClientFactory类代码示例发布时间: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