Exemple #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)
	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()
Exemple #3
0
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)
Exemple #4
0
    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"])
Exemple #5
0
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])
Exemple #6
0
    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)
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
Exemple #8
0
    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()
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})
Exemple #10
0
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()
Exemple #11
0
 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)
Exemple #12
0
 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)
Exemple #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() # 代理服务暂停数据接收
Exemple #14
0
 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
Exemple #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)
Exemple #16
0
 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
Exemple #17
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)))
Exemple #18
0
 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
Exemple #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
Exemple #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)))
Exemple #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))
Exemple #22
0
    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)
Exemple #23
0
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)
Exemple #24
0
    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()
Exemple #25
0
 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)
Exemple #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()
def main(reactor):
    cc = ClientCreator(reactor, AMP)
    d = cc.connectTCP('localhost', 7805)
    d.addCallback(otpLogin)
    d.addCallback(add)
    d.addCallback(display)
    return d
    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)
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)
Exemple #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)
Exemple #31
0
def sendCommand(command):
    def test(d):
        print "Invio ->", command
        d.sendCommand(command)

    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)
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
Exemple #33
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)
Exemple #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()
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()
Exemple #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()
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)
	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)
    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
Exemple #40
0
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))
Exemple #41
0
def sendCommand(command):
    def test(d):
        print "Invio ->", command
        d.sendCommand(command)

    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)
Exemple #42
0
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)
Exemple #43
0
 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)
Exemple #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
Exemple #45
0
def main(reactor):
    cc = ClientCreator(reactor, AMP)
    d = cc.connectTCP('localhost', 7805)
    d.addCallback(otpLogin)
    d.addCallback(add)
    d.addCallback(display)
    return d
Exemple #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()
Exemple #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)
Exemple #48
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
Exemple #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
Exemple #50
0
    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
    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()
Exemple #52
0
 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
Exemple #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
 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
Exemple #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)
	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)
Exemple #57
0
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