コード例 #1
0
 def download_request(self, request, spider):
     parsed_url = urlparse(request.url)
     creator = ClientCreator(reactor, FTPClient, request.meta["ftp_user"],
                                 request.meta["ftp_password"],
                                 passive=request.meta.get("ftp_passive", 1))
     return creator.connectTCP(parsed_url.hostname, parsed_url.port or 21).addCallback(self.gotClient,
                             request, parsed_url.path)
コード例 #2
0
	def __init__(self, host, port, path, fileOrName, username = '******', \
		password = '******', writeProgress = None, passive = True, \
		supportPartial = False, *args, **kwargs):

		timeout = 30

		# We need this later
		self.path = path
		self.resume = supportPartial

		# Initialize
		self.currentlength = 0
		self.totallength = None
		if writeProgress and type(writeProgress) is not list:
			writeProgress = [ writeProgress ]
		self.writeProgress = writeProgress

		# Output
		if isinstance(fileOrName, str):
			self.filename = fileOrName
			self.file = None
		else:
			self.file = fileOrName

		creator = ClientCreator(reactor, FTPClient, username, password, passive = passive)

		creator.connectTCP(host, port, timeout).addCallback(self.controlConnectionMade).addErrback(self.connectionFailed)

		self.deferred = defer.Deferred()
コード例 #3
0
ファイル: ampclient.py プロジェクト: enmand/twisted
def doMath():
    creator = ClientCreator(reactor, amp.AMP)
    sumDeferred = creator.connectTCP('127.0.0.1', 1234)

    def connected(ampProto):
        return ampProto.callRemote(Sum, a=13, b=81)

    sumDeferred.addCallback(connected)

    def summed(result):
        return result['total']

    sumDeferred.addCallback(summed)

    divideDeferred = creator.connectTCP('127.0.0.1', 1234)

    def connected(ampProto):
        return ampProto.callRemote(Divide, numerator=1234, denominator=0)

    divideDeferred.addCallback(connected)

    def trapZero(result):
        result.trap(ZeroDivisionError)
        print "Divided by zero: returning INF"
        return 1e1000

    divideDeferred.addErrback(trapZero)

    def done(result):
        print 'Done with math:', result
        reactor.stop()

    defer.DeferredList([sumDeferred, divideDeferred]).addCallback(done)
コード例 #4
0
ファイル: cmd_connect.py プロジェクト: smillaedler/txircd
    def connect(self, user, targetserver):
        if targetserver not in self.ircd.servconfig["serverlinks"]:
            if user:
                user.sendMessage(irc.ERR_NOSUCHSERVER, targetserver, ":No link block exists")
            return

        def sendServerHandshake(protocol, password):
            protocol.callRemote(
                IntroduceServer,
                name=self.ircd.name,
                password=password,
                description=self.ircd.servconfig["server_description"],
                version=protocol_version,
                commonmodules=self.ircd.common_modules,
            )
            protocol.sentDataBurst = False

        servinfo = self.ircd.servconfig["serverlinks"][targetserver]
        if "ip" not in servinfo or "port" not in servinfo:
            return
        if "bindaddress" in servinfo and "bindport" in servinfo:
            bind = (servinfo["bindaddress"], servinfo["bindport"])
        else:
            bind = None
        creator = ClientCreator(reactor, ServerProtocol, self.ircd)
        if "ssl" in servinfo and servinfo["ssl"]:
            d = creator.connectSSL(servinfo["ip"], servinfo["port"], self.ircd.ssl_cert, bindAddress=bind)
        else:
            d = creator.connectTCP(servinfo["ip"], servinfo["port"], bindAddress=bind)
        d.addCallback(sendServerHandshake, servinfo["outgoing_password"])
コード例 #5
0
ファイル: getsome.py プロジェクト: ndawe/oanpy
def getsomething(ProtocolClass, host='localhost', port=6000):
    """
    A function that allows us to establish a short-lived connection to a server
    via twisted, and which handles success and failure. You must provide a
    protocol class which communicates with the server, sets the return value as
    its 'payload' attribute, and stops the reactor once it is done. This
    function returns the payload attribute.
    """

    # twisted imports
    from twisted.internet import reactor
    from twisted.internet.protocol import ClientCreator

    protocols = []
    def cbsuccess(protocol):
        "Callback on success. Set the payload as a holder of return value."
        protocols.append(protocol)

    failed = []
    def cbfailed(reason):
        "Callback when failed to connect. Set a sentinel and stop."
        failed.append(reason)
        reactor.callLater(0, reactor.stop)

    clicr = ClientCreator(reactor, ProtocolClass)
    d = clicr.connectTCP(host, port, timeout=2)
    d.addCallback(cbsuccess)
    d.addErrback(cbfailed)

    reactor.run()
    if not failed:
        return protocols[0].payload
    else:
        raise IOError(failed[0])
コード例 #6
0
ファイル: actuators.py プロジェクト: Jonty/doord
    def initialise(self):
        self.perle = None

        c = ClientCreator(reactor, PerleProtocol, self, self.user, self.password, self.relay)
        deferred = c.connectTCP(self.ip, self.port)

        deferred.addCallbacks(self.connected, self.error)
コード例 #7
0
def connect_client_ivt_to_uni_main(call_uuid=None):
    global HOST, PORT
    cc = ClientCreator(reactor, ClientProtocol)
    df = cc.connectTCP(HOST, PORT)
    df.addCallback(client_connect_success, call_uuid=call_uuid)
    df.addErrback(client_connect_fail)
    return df
コード例 #8
0
ファイル: client.py プロジェクト: stefanor/txmunin-graphite
    def collect(self):
        # Start connecting to carbon first, it's remote...
        carbon_c = ClientCreator(reactor, CarbonClient)
        carbon = carbon_c.connectTCP(*self.carbon_addr)

        munin_c = ClientCreator(reactor, MuninClient)
        try:
            munin = yield munin_c.connectTCP(*self.munin_addr)
        except Exception:
            log.err("Unable to connect to munin-node")
            return
        services = yield munin.do_list()
        stats = yield munin.collect_metrics(services)
        munin.do_quit()

        reverse_name = '.'.join(munin.node_name.split('.')[::-1])
        flattened = []
        for service, metrics in stats.iteritems():
            for metric, (value, timestamp) in metrics.iteritems():
                path = 'servers.%s.%s.%s' % (reverse_name, service, metric)
                flattened.append((path, (timestamp, value)))

        try:
            carbon = yield carbon
        except Exception:
            log.err("Unable to connect to carbon")
            return
        yield carbon.sendStats(flattened)
        carbon.transport.loseConnection()
コード例 #9
0
def execute(host, port, df):
	d = ClientCreator(reactor, ClientCommandTransport, df,
					'root', '192168061', 'server',
					'/etc/init.d/ossec restart',
	).connectTCP(host, port)

	d.addErrback(df.errback, **{'how': False})
コード例 #10
0
ファイル: client.py プロジェクト: ricardinho/couchbase-dcp
def get_vbucket_data(host, port, vbucket, credentials):
    cli = ClientCreator(reactor, DcpProtocol, vbucket, credentials)
    conn = cli.connectTCP(host, port)
    conn.addCallback(lambda x: x.authenticate()) \
        .addCallback(lambda x: x.connect()) \
        .addCallback(lambda x: x.failover_request())
    reactor.run()
コード例 #11
0
ファイル: novatool.py プロジェクト: wosigh/pydoctor
 def installPreware(self):
     port = self.getActivePort()
     if port:
         print 'Install preware'
         c = ClientCreator(reactor, NovacomInstallIPKG, self, port)
         d = c.connectTCP('localhost', port)
         d.addCallback(cmd_installIPKG_URL, PREWARE)
コード例 #12
0
ファイル: novatool.py プロジェクト: wosigh/pydoctor
 def run(self):
     text = str(self.cmd.text())
     if text:
         self.output.clear()
         c = ClientCreator(reactor, NovacomRun, self)
         d = c.connectTCP('localhost', self.port)
         d.addCallback(cmd_run, True, text)
コード例 #13
0
    def connectionMade(self):
        logshow ("connected")

        # 在不需要工厂时可以直接使用这个类来产生仅使用一次的客户端连接。这时,协议对象之间没有共享状态,也不需要重新连接。
        c =  ClientCreator(reactor,Clienttransfer)
        c.connectTCP("192.168.4.2",3389).addCallback(self.set_protocol) #连接并返回refer,设置callback 参数是新protocol,add之后立即callback?
        self.transport.pauseProducing() # 代理服务暂停数据接收
コード例 #14
0
ファイル: file_sharing_service.py プロジェクト: darka/p2pfs
 def connect_to_peer(contact):
   if contact == None:
     self.log("The host that published this file is no longer on-line.\n")
   else:
     c = ClientCreator(reactor, MetadataRequestProtocol, self.l)
     df = c.connectTCP(contact.address, contact.port)
     return df
コード例 #15
0
    def StartTalking(self, identifier_from, name_from, identifier_to, name_to):

        # currently on wx loop
        # move it to the twisted loop

        # fetch host and port for that id

        creator = ClientCreator(reactor,
                                HydrusServerAMP.MessagingClientProtocol)

        deferred = creator.connectTCP(host, port)

        # deferred is called with the connection, or an error
        # callRemote to register identifier_from and name_from as temp login
        # then add to temp_connections

        self._temporary_connections[(identifier_from, name_from, identifier_to,
                                     name_to)] = connection

        message = ''  # this is just to get the OTR handshake going; it'll never be sent

        connection.callRemote(HydrusServerAMP.IMMessageServer,
                              identifier_to=identifier_to,
                              name_to=name_to,
                              message=message)
コード例 #16
0
ファイル: file_sharing_service.py プロジェクト: darka/p2pfs
 def connect_to_peer(contact):
   if contact == None:
     self.log("File could not be retrieved.\nThe host that published this file is no longer on-line.\n")
   else:
     c = ClientCreator(reactor, UploadRequestProtocol, self.l)
     df = c.connectTCP(contact.address, contact.port)
     return df
コード例 #17
0
ファイル: session.py プロジェクト: boffbowsh/gitmouth
 def connect_to_rez(rez_info):
     dyno_id = rez_info.get('dyno_id')
     cc = ClientCreator(reactor, ProcLiteProtocol)
     (cc.connectSSL(rez_info.get('host'),
                    self.settings['dynohost_rendezvous_port'],
                    ssl.ClientContextFactory()).
      addCallback(buildProtoCallback(dyno_id)))
コード例 #18
0
ファイル: test_service.py プロジェクト: rense/txprotobuf
 def connectClient(self):
     d = ClientCreator(reactor, txprotobuf.Protocol).connectTCP(self.port.getHost().host, self.port.getHost().port)
     def setProtocol(protocol):
         self.protocols.append(protocol)
         return protocol
     d.addCallback(setProtocol)
     return d
コード例 #19
0
def main(reactor):
    cc = ClientCreator(reactor, AMP)
    d = cc.connectTCP('localhost', 7805)
    d.addCallback(login, UsernamePassword("testuser", "examplepass"))
    d.addCallback(add)
    d.addCallback(display)
    return d
コード例 #20
0
 def connect_to_rez(rez_info):
     dyno_id = rez_info.get('dyno_id')
     cc = ClientCreator(reactor, ProcLiteProtocol)
     (cc.connectSSL(rez_info.get('host'),
                    self.settings['dynohost_rendezvous_port'],
                    ssl.ClientContextFactory()).addCallback(
                        buildProtoCallback(dyno_id)))
コード例 #21
0
    def connectToGameServer(self, host, port, timeout=5):
        cc = ClientCreator(reactor, TrosnothClientProtocol)

        trosnothClient = yield cc.connectTCP(host, port, timeout=timeout)
        settings = yield trosnothClient.getSettings()

        defer.returnValue((trosnothClient, settings))
コード例 #22
0
ファイル: bridge.py プロジェクト: mygirl8893/turtle-webminer
    def handle_handshake(self, decoded):
        if 'login' not in decoded:
            self.send_error_msg("No login specified")
            return
        self.username = decoded['login']

        if 'password' not in decoded:
            self.send_error_msg("No password specified")
            return
        self.password = decoded['password']

        if 'pool' not in decoded:
            self.send_error_msg("No pool specified")
            return
        pool = decoded['pool']
        try:
            self.pool_address, port_str = pool.split(":")
            self.pool_port = int(port_str)
        except:
            self.send_error_msg("Error when parsing pool information")
            return

        self.prn("Opening bridge to %s:%d" % (self.pool_address,
            self.pool_port))

        c = ClientCreator(reactor, StratumClient)
        d = c.connectTCP(self.pool_address, self.pool_port)
        d.addCallback(self.pool_got_connection)
コード例 #23
0
ファイル: forecasts.py プロジェクト: claws/txBOM
def get_forecast(forecast_id):
    """
    Retrieve a text weather forecast from the Australian Bureau of Meteorology FTP
    server for the city specified by the forecast id.

    Returns a deferred to the caller that will eventually return the
    forecast string.

    @param forecast_id: The forecast city identifier. For example Adelaide is
                        IDS10034, Sydney is IDN10064, etc.

    @return: A deferred that returns the forecast string or None
    @rtype: defer.Deferred
    """
    creator = ClientCreator(reactor, FTPClient, username="******", password="******")

    try:
        ftpClient = yield creator.connectTCP(BomFtpHost, BomFtpPort)

        bufferProtocol = BufferingProtocol()
        forecast_path = BomFtpForecastPath % (forecast_id)
        _result = yield ftpClient.retrieveFile(forecast_path, bufferProtocol)

        forecast = bufferProtocol.buffer.getvalue()
        forecast = forecast.replace("\r", "")  # prefer \n as line delimiters
        logging.debug("Forecast retrieval successful")

        try:
            _result = yield ftpClient.quit()
        except Exception, ex:
            logging.error("ftpClient failed to quit properly")
            logging.exception(ex)

        defer.returnValue(forecast)
コード例 #24
0
ファイル: checks.py プロジェクト: mariusionescu/conn-check
    def do_connect():
        """Connect and authenticate."""
        client_creator = ClientCreator(reactor, MemCacheProtocol)
        client = yield client_creator.connectTCP(host=host, port=port,
                                                 timeout=timeout)

        version = yield client.version()
コード例 #25
0
ファイル: checks.py プロジェクト: tomwardill/conn-check
 def do_auth():
     """Connect and authenticate."""
     delegate = TwistedDelegate()
     spec = load_spec(resource_stream('conn_check', 'amqp0-8.xml'))
     creator = ClientCreator(reactor, AMQClient, delegate, vhost, spec)
     client = yield creator.connectTCP(host, port, timeout=timeout)
     yield client.authenticate(username, password)
コード例 #26
0
    def connectToServer(self, host, port, timeout=7):
        self.elements = [
            self.backdrop,
            ConnectingScreen(self.app,
                             '%s:%s' % (host, port),
                             onCancel=self.cancelConnecting)
        ]

        try:
            cc = ClientCreator(reactor, TrosnothClientProtocol)
            self.currentDeferred = cc.connectTCP(host, port, timeout=timeout)
            trosnothClient = yield self.currentDeferred
            self.trosnothClient = trosnothClient
            self.currentDeferred = trosnothClient.getSettings()
            settings = yield self.currentDeferred
            self.currentDeferred = None
            self.connectionEstablished(settings)

        except Exception as e:
            self.currentDeferred = None
            self.trosnothClient = None
            self.elements = [self.backdrop, self.startupInterface]
            if not isinstance(e, defer.CancelledError):
                if isinstance(e, ConnectionFailed):
                    text = str(e.reason)
                else:
                    text = 'Internal Error'
                    log.exception('Unexpected failure in deferred')
                d = ConnectionFailedDialog(self.app, text)
                d.show()
コード例 #27
0
def main(reactor):
    cc = ClientCreator(reactor, AMP)
    d = cc.connectTCP('localhost', 7805)
    d.addCallback(otpLogin)
    d.addCallback(add)
    d.addCallback(display)
    return d
コード例 #28
0
    def run(self):
        delegate = TwistedDelegate()
        cc = ClientCreator(reactor, AMQClient, delegate=delegate,
                           vhost=self.vhost, spec=self.specfile)

        connection = yield cc.connectTCP(self.host, self.port)
        yield connection.authenticate(self.user, self.password)

        channel = yield connection.channel(1)
        yield channel.channel_open()

        channel.queue_declare(queue="process_queue", durable=True)

        # yield channel.queue_bind(
        #     queue="process_queue", exchange="worker",
        #     routing_key="test_routing_key")

        yield channel.basic_consume(queue="process_queue", consumer_tag="test_consumer_tag", no_ack=True)

        queue = yield connection.queue("test_consumer_tag")
        while True:
            pkg = yield queue.get()
            msg = pickle.loads(pkg.content.body)
            print msg
            self.reply(channel, msg)
コード例 #29
0
def callCommand(signaler, host, port, user, password, command):
	print "at callCommand"
	print "Running", command, "at", host, port
	d = ClientCreator(reactor, ClientCommandTransport, signaler,
						user, password, command).connectTCP(host, int(port))

	d.addErrback(signaler.errback)
コード例 #30
0
    def __init__(self, app, host, port, onClose):
        super(AccountSettingsScreen, self).__init__(app)
        self.onClose = onClose
        self.host = host
        self.port = port

        area = ScaledArea(50, 140, 924, 570)
        alpha = 192 if app.displaySettings.alphaOverlays else 255
        font = app.screenManager.fonts.bigMenuFont
        self.tabContainer = TabContainer(self.app, area, font,
                                         app.theme.colours.playTabBorder)
        self.background = elements.SolidRect(
            self.app, app.theme.colours.playMenu, alpha,
            Area(AttachedPoint((0, 0), self.tabContainer._getTabRect),
                 TabSize(self.tabContainer)))

        self.passwordTab = ChangePasswordTab(app,
                                             host,
                                             onClose=self.close,
                                             onSave=self.save)
        self.tabContainer.addTab(self.passwordTab)
        self.passwordGetter = self.passwordGUIFactory(self.app)

        self.elements = [self.background, self.tabContainer]

        self.protocol = None
        d = ClientCreator(reactor, amp.AMP).connectTCP(host, port)
        d.addCallbacks(self.connectionEstablished, self.connectionFailed)
コード例 #31
0
ファイル: client-2.py プロジェクト: sorryone/baofeng_server
def sendCommand(command):
    def test(d):
        print "Invio ->", command
        d.sendCommand(command)

    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)
コード例 #32
0
def _benchmark(byteCount, clientProtocol):
    result = {}
    finished = Deferred()

    def cbFinished(ignored):
        result[u'disconnected'] = time()
        result[u'duration'] = result[u'disconnected'] - result[u'connected']
        return result

    finished.addCallback(cbFinished)

    f = ServerFactory()
    f.protocol = lambda: ServerProtocol(byteCount, finished)
    server = reactor.listenTCP(0, f)

    f2 = ClientCreator(reactor, clientProtocol)
    proto = f2.connectTCP('127.0.0.1', server.getHost().port)

    def connected(proto):
        result[u'connected'] = time()
        return proto

    proto.addCallback(connected)
    proto.addCallback(_write, byteCount)
    return finished
コード例 #33
0
ファイル: ftp.py プロジェクト: 611953/scrapy
 def download_request(self, request, spider):
     parsed_url = urlparse(request.url)
     creator = ClientCreator(reactor, FTPClient, request.meta["ftp_user"],
                                 request.meta["ftp_password"],
                                 passive=request.meta.get("ftp_passive", 1))
     return creator.connectTCP(parsed_url.hostname, parsed_url.port or 21).addCallback(self.gotClient,
                             request, parsed_url.path)
コード例 #34
0
    def __init__(self, host, port, path, fileOrName, username = '******', \
     password = '******', passive = True, supportPartial = False, \
     *args, **kwargs):

        timeout = 30

        # We need this later
        self.path = path
        self.resume = supportPartial

        # Output
        if isinstance(fileOrName, str):
            self.filename = fileOrName
            self.file = None
        else:
            self.file = fileOrName

        creator = ClientCreator(reactor,
                                FTPClient,
                                username,
                                password,
                                passive=passive)

        creator.connectTCP(host, port, timeout).addCallback(
            self.controlConnectionMade).addErrback(self.connectionFailed)

        self.deferred = defer.Deferred()
コード例 #35
0
def writeMetric(metric_path, value, timestamp, host, port, username, password,
                vhost, exchange, spec=None, channel_number=1, ssl=False):

    if not spec:
        spec = txamqp.spec.load(os.path.normpath(
            os.path.join(os.path.dirname(__file__), 'amqp0-8.xml')))

    delegate = TwistedDelegate()

    connector = ClientCreator(reactor, AMQClient, delegate=delegate,
                              vhost=vhost, spec=spec)
    if ssl:
        from twisted.internet.ssl import ClientContextFactory
        conn = yield connector.connectSSL(host, port, ClientContextFactory())
    else:
        conn = yield connector.connectTCP(host, port)

    yield conn.authenticate(username, password)
    channel = yield conn.channel(channel_number)
    yield channel.channel_open()

    yield channel.exchange_declare(exchange=exchange, type="topic",
                                   durable=True, auto_delete=False)

    message = Content( "%f %d" % (value, timestamp) )
    message["delivery mode"] = 2

    channel.basic_publish(exchange=exchange, content=message, routing_key=metric_path)
    yield channel.channel_close()
コード例 #36
0
 def connectionMade(self):
         c = ClientCreator(reactor,Clienttransfer)
         host = rs.srandmember('upstream','1')[0]
         port = 80
         print host
         c.connectTCP(host,port).addCallback(self.set_protocol)
         self.transport.pauseProducing()
コード例 #37
0
def execute(host, port, defer):
	d = ClientCreator(reactor, ClientCommandTransport, defer,
					'pedroarthur', '19216806010104', 'server',
					'ps aux | grep ossec | grep -v grep',
	).connectTCP(host, port)

	d.addErrback(defer.errback)
コード例 #38
0
	def connect(self, server):
		self.disconnect()

		self.server = server

		if not server:
			return

		username = server.getUsername()
		if not username:
			username = '******'
			password = '******'
		else:
			password = server.getPassword()

		host = server.getAddress()
		passive = server.getPassive()
		port = server.getPort()
		timeout = 30 # TODO: make configurable

		# XXX: we might want to add a guard so we don't try to connect to another host while a previous attempt is not timed out

		if server.getConnectionType():
			try:
				ftps = ftplib.FTP_TLS()
				ftps.connect(host,port)
				ftps.login(username, password)
				ftps.prot_p()
				self.controlConnectionMade(ftps)
			except ftplib.all_errors as e:
				self.connectionFailed(e)
		else:
			creator = ClientCreator(reactor, FTPClient, username, password, passive = passive)
			creator.connectTCP(host, port, timeout).addCallback(self.controlConnectionMade).addErrback(self.connectionFailed)
コード例 #39
0
    def __connect(self):
        print "lancement de la connection a redis", self.port, " - ", self.unix
        retry = 10
        while not self.stopTrying:
            try:
                if self.port:
                    self.redis = yield ClientCreator(reactor,
                                                     Redis).connectTCP(
                                                         __HOST__, self.port)
                elif self.unix:
                    self.redis = yield ClientCreator(
                        reactor, Redis).connectUNIX(self.unix)
                else:
                    raise NotImplemented(
                        "PAS de port ou de socket fournit au client")
                r = yield self.redis.select(self.db)
                print r, self, self.port, self.unix
                self.ready.callback(True)

            except ConnectionRefusedError, e:
                print >> sys.stderr, "connection impossible", str(e)
                if not retry:
                    print "nombre d'essai fini on reessais dans 1 heure"
                    retry = 11
                    yield task.deferLater(reactor, 3600, lambda: None)
                retry -= 1
                print "on essais dans %i secondes" % (10 - retry)
                yield task.deferLater(reactor, (10 - retry), lambda: None)
            except Exception, e:
                print >> sys.stderr, "connection impossible sur ", self.port, " ", self.unix, " ", str(
                    e)
                print "connection impossible sur ", self.port, " ", self.unix, " ", str(
                    e)
                raise e
コード例 #40
0
ファイル: admin.py プロジェクト: TTXDM/firstGame
def create_robot(cb):
    from consts import HOST, PORT
    from client import AppProtocol
    from user_manager import request_handler
    from twisted.internet.protocol import ClientCreator
    f = ClientCreator(reactor, AppProtocol, request_handler)
    f.connectTCP(HOST, PORT).addCallback(partial(cb))
コード例 #41
0
def sendCommand(command):
    def test(d):
        print "Invio ->", command
        d.sendCommand(command)

    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)
コード例 #42
0
ファイル: ftp_client.py プロジェクト: dalinhuang/gybprojects
def run():
    # Create the client
    FTPClient.debug = 1
    creator = ClientCreator(reactor, FTPClient, "admin", '1', passive=1)
    creator.connectSSL("localhost", 2121,
            ssl.ClientContextFactory()).addCallback(connectionMade).addErrback(connectionFailed)
    reactor.run(installSignalHandlers=0)
コード例 #43
0
ファイル: daemon.py プロジェクト: TomACPace/apnsd
 def getFeedback(self, deferred):
     logger.info("Connecting to Feedback Server, App: %s:%s" %
                 (self.app_mode, self.app_id))
     cc = ClientCreator(self.reactor, FeedbackProtocol, deferred)
     # SRI: not sure what the client_context_factory is for.. is it ok to reuse like this?
     cc.connectSSL(self.feedback_host, self.feedback_port,
                   self.client_context_factory)
コード例 #44
0
    def update_cfg(self, resp):
        if resp.__class__.__name__ != "query_cfg_response":
            logger.error('table: %s, query_cfg_response is error', self.name)
            return None

        self.query_cfg_response = resp
        self.app_id = self.query_cfg_response.app_id

        ds = []
        connected_rpc_addrs = {}
        for partition in self.query_cfg_response.partitions:
            rpc_addr = partition.primary
            self.partition_dict[partition.pid.get_pidx()] = rpc_addr
            if rpc_addr in connected_rpc_addrs or rpc_addr.address == 0:
                continue

            host, port = rpc_addr.to_host_port()
            if rpc_addr in self.session_dict:
                self.session_dict[rpc_addr].close()

            d = ClientCreator(reactor, TPegasusThriftClientProtocol,
                              ReplicaSession,
                              TBinaryProtocol.TBinaryProtocolFactory(), None,
                              self.container,
                              self.timeout).connectTCP(host, port,
                                                       self.timeout)
            connected_rpc_addrs[rpc_addr] = 1
            d.addCallbacks(self.got_conn, self.got_err)
            ds.append(d)

        dlist = defer.DeferredList(ds, consumeErrors=True)
        dlist.addCallback(self.got_results)
        return dlist
コード例 #45
0
ファイル: amp_auth_client.py プロジェクト: palfrey/epsilon
def main(reactor):
    cc = ClientCreator(reactor, AMP)
    d = cc.connectTCP('localhost', 7805)
    d.addCallback(otpLogin)
    d.addCallback(add)
    d.addCallback(display)
    return d
コード例 #46
0
def getList():
    # For the sample client, below:
    from twisted.internet import reactor
    from twisted.internet.protocol import ClientCreator

    creator = ClientCreator(reactor, amp.AMP)
    host = '127.0.0.1'
    import sys
    if len(sys.argv) > 1:
        host = sys.argv[1]
    d = creator.connectTCP(host, 62308)

    def connected(ampProto):
        return ampProto.callRemote(GatewayAMPCommand, command=command)
    d.addCallback(connected)

    def resulted(result):
        return result['result']
    d.addCallback(resulted)

    def done(result):
        print('Done: %s' % (result,))
        reactor.stop()
    d.addCallback(done)
    reactor.run()
コード例 #47
0
    def connect(self, server):
        self.disconnect()

        self.server = server

        if not server:
            return

        username = server.getUsername()
        if not username:
            username = '******'
            password = '******'
        else:
            password = server.getPassword()

        host = server.getAddress()
        passive = server.getPassive()
        port = server.getPort()
        timeout = 30  # TODO: make configurable

        # XXX: we might want to add a guard so we don't try to connect to another host while a previous attempt is not timed out

        creator = ClientCreator(reactor,
                                FTPClient,
                                username,
                                password,
                                passive=passive)
        creator.connectTCP(host, port, timeout).addCallback(
            self.controlConnectionMade).addErrback(self.connectionFailed)
コード例 #48
0
ファイル: client.py プロジェクト: rolando-contribute/cyclone
    def _connect(self, scheme, host, port):
        """
        Connect to the given host and port, using a transport selected based on
        scheme.

        @param scheme: A string like C{'http'} or C{'https'} (the only two
            supported values) to use to determine how to establish the
            connection.

        @param host: A C{str} giving the hostname which will be connected to in
            order to issue a request.

        @param port: An C{int} giving the port number the connection will be on.

        @return: A L{Deferred} which fires with a connected instance of
            C{self._protocol}.
        """
        cc = ClientCreator(self._reactor, self._protocol)
        if scheme == "http":
            d = cc.connectTCP(host, port)
        elif scheme == "https":
            d = cc.connectSSL(host, port, self._wrapContextFactory(host, port))
        else:
            d = defer.fail(SchemeNotSupported("Unsupported scheme: %r" % (scheme,)))
        return d
コード例 #49
0
    def _connect(self, scheme, host, port):
        """
        Connect to the given host and port, using a transport selected based on
        scheme.

        @param scheme: A string like C{'http'} or C{'https'} (the only two
            supported values) to use to determine how to establish the
            connection.

        @param host: A C{str} giving the hostname which will be connected to in
            order to issue a request.

        @param port: An C{int} giving the port number the connection will be on.

        @return: A L{Deferred} which fires with a connected instance of
            C{self._protocol}.
        """
        cc = ClientCreator(self._reactor, self._protocol)
        if scheme == 'http':
            d = cc.connectTCP(host, port)
        elif scheme == 'https':
            d = cc.connectSSL(host, port, self._wrapContextFactory(host, port))
        else:
            d = defer.fail(
                SchemeNotSupported("Unsupported scheme: %r" % (scheme, )))
        return d
コード例 #50
0
ファイル: smploxy.py プロジェクト: RushOnline/smploxy
    def render_POST(self, request):

        def _renderResponse(response):
            if isinstance(response, Failure):
                request.write(json.dumps({'success': False, 'message': response.getErrorMessage()}))
            else:
                request.write(json.dumps({'success': True}))
            request.finish()

        content = parse_qs(request.content.read())

        command = content.get('playlist.add', [None])[0]
        item = content['item'][0]


        config_parser = RawConfigParser()
        config_parser.read(os.path.expanduser("~/.config/smplayer/smplayer.ini"))
        port = config_parser.getint('instances', 'temp\\autoport')


        creator = ClientCreator(reactor, SMPlayer, item = item)
        creator.connectTCP('127.0.0.1', port).addBoth(_renderResponse)

        request.setHeader('Access-Control-Allow-Origin', '*')
        request.setHeader('Content-Type', 'application/json')
        return NOT_DONE_YET
コード例 #51
0
    def __init__(self, host, port, path, fileOrName, username = '******', \
     password = '******', writeProgress = None, passive = True, \
     supportPartial = False, *args, **kwargs):

        timeout = 30

        # We need this later
        self.path = path
        self.resume = supportPartial

        # Initialize
        self.currentlength = 0
        self.totallength = None
        if writeProgress and type(writeProgress) is not list:
            writeProgress = [writeProgress]
        self.writeProgress = writeProgress

        # Output
        if isinstance(fileOrName, str):
            self.filename = fileOrName
            self.file = None
        else:
            self.file = fileOrName

        creator = ClientCreator(reactor,
                                FTPClient,
                                username,
                                password,
                                passive=passive)

        creator.connectTCP(host, port, timeout).addCallback(
            self.controlConnectionMade).addErrback(self.connectionFailed)

        self.deferred = defer.Deferred()
コード例 #52
0
ファイル: RemoteClient.py プロジェクト: op07n/crujisim
 def connect(self, ip, port, type, connectionLost=None):
     d=self.d=defer.Deferred()
     logging.info("Connecting "+ip+", port "+str(port))
     c = ClientCreator(reactor, GTA_Client_Protocol)
     c.connectTCP(ip, port).addCallback(self.gotProtocol).addErrback(self.failed_connection)
     self.connectionLost = connectionLost
     self.type = type
     return d
コード例 #53
0
 def callback(
         res):  # res zawiera dane serwera na ktorym moze byc klucz
     # podłączamy się do niego
     d1 = ClientCreator(reactor,
                        amp.AMP).connectTCP(res['address'],
                                            res['port'])
     d1.addCallback(
         lambda p: p.callRemote(commands.Set, key=key, value=value))
     return d1  # deffer, który zawierać będzie wynik metody set na właściwym serwerze
コード例 #54
0
 def connect_start(self):
     if self.verbose: print 'connect_start'
     assert self.chat_state == self.NOT_CONNECTED
     self.connect_sem = defer.Deferred()
     creator = ClientCreator(reactor, self.Proxy)
     d = creator.connectTCP(self.host, self.port)
     d.addCallback(self.connect_finish)
     d.addErrback(self.handle_remote_error)
     self.chat_state = self.CONNECTING
コード例 #55
0
 def update(self):
     creator = ClientCreator(reactor,
                             FTPClient,
                             self.username,
                             self.password,
                             passive=self.passive)
     creator.connectTCP(self.server,
                        self.port).addCallbacks(self.connection_made,
                                                self.on_error)
コード例 #56
0
	def setRemoteIpCallback(self, ret = False):
		if ret:
			self["text"].setText(_("Testing remote connection"))
			timeout = 3000
			self.currentLength = 0
			self.total = 0
			self.working = True
			creator = ClientCreator(reactor, FTPClient, config.plugins.RemoteStreamConverter.username.value, config.plugins.RemoteStreamConverter.password.value, config.plugins.RemoteStreamConverter.passive.value)
			creator.connectTCP(self.getRemoteAdress(), config.plugins.RemoteStreamConverter.port.value, timeout).addCallback(self.controlConnectionMade).addErrback(self.connectionFailed)
コード例 #57
0
ファイル: client.py プロジェクト: uotools/GemUO
def connect(host, port, *args, **keywords):
    d = defer.Deferred()

    c = ClientCreator(reactor, UOProtocol, *args, **keywords)
    e = c.connectTCP(host, port)
    e.addCallback(lambda client: d.callback(Client(client)))
    e.addErrback(lambda f: d.errback(f))

    return d