コード例 #1
0
ファイル: pokerrestclient.py プロジェクト: arem/poker-network
 def sendPacketData(self, data):
     if self.verbose > 3:
         self.message('sendPacketData ' + data)
     factory = RestClientFactory(self.host, self.port, self.path, data, self.timeout)
     reactor.connectTCP(self.host, self.port, factory)
     self.sentTime = seconds()
     return factory.deferred
コード例 #2
0
ファイル: core.py プロジェクト: ojii/bottu
 def run(self):
     log.msg("Running bot as %r" % self.name)
     self.irc = BottuClientFactory(self)
     self.join_passive_channel.ready()
     reactor.connectTCP(self.network, self.port, self.irc)
     reactor.run()
     log.msg("Stopping bot")
コード例 #3
0
    def testWriter(self):
        f = protocol.Factory()
        f.protocol = LargeBufferWriterProtocol
        f.done = 0
        f.problem = 0
        f.len = self.datalen
        p = reactor.listenTCP(0, f, interface="127.0.0.1")
        n = p.getHost().port
        self.ports.append(p)
        clientF = LargeBufferReaderClientFactory()
        reactor.connectTCP("127.0.0.1", n, clientF)

        while 1:
            rxlen = clientF.len
            try:
                spinUntil(lambda :f.done and clientF.done, timeout=30)
            except defer.TimeoutError:
                if clientF.len == rxlen:
                    raise
                # if we're still making progress, keep trying
                continue
            break

        self.failUnless(f.done, "writer didn't finish, it probably died")
        self.failUnless(clientF.len == self.datalen,
                        "client didn't receive all the data it expected "
                        "(%d != %d)" % (clientF.len, self.datalen))
        self.failUnless(clientF.done, "client didn't see connection dropped")
コード例 #4
0
ファイル: proxies.py プロジェクト: jookies/jasmin
    def connect(self, host, port, username=None, password=None, retry=False):
        if retry:
            # Launch a client
            self.pbClientFactory = ReconnectingPBClientFactory()
            self.pbClientFactory.gotPerspective = self._connected
            self.pbClientFactory.disconnected = self._disconnected

            # Start login
            if username is None and password is None:
                self.pbClientFactory.startLogin(
                    Anonymous())
            else:
                self.pbClientFactory.startLogin(
                    UsernamePassword(
                        username,
                        password))

            reactor.connectTCP(host, port, self.pbClientFactory)
        else:
            # Launch a client
            self.pbClientFactory = pb.PBClientFactory()
            reactor.connectTCP(host, port, self.pbClientFactory)

            yield self.pbClientFactory.getRootObject()

            if username is None and password is None:
                yield self.pbClientFactory.login(
                    Anonymous()).addCallback(self._connected)
            else:
                yield self.pbClientFactory.login(
                    UsernamePassword(
                        username,
                        password)).addCallback(self._connected)
コード例 #5
0
ファイル: feedbackengine.py プロジェクト: AlexHendy98/iris
 def render_POST(self, request):
   text = request.args.get("feedback")
   if text is None:
     raise FeedbackException("No text.")
   if len(text) > 50000:
     raise FeedbackException("Too much text.")
     
   text = text[0]
   
   # basic checksum to stop really lame kiddies spamming, see feedback.js for js version
   checksum = 0;
   text = text.decode("utf-8", "ignore")
   for x in text:
     checksum = ((checksum + 1) % 256) ^ (ord(x) % 256);
   
   sentchecksum = int(request.args.get("c", [0])[0])
   if checksum != sentchecksum:
     raise FeedbackException("Bad checksum: %d vs. %d" % (sentchecksum, checksum))
     
   msg = MIMEText(text.encode("utf-8"), _charset="utf-8")
   msg["Subject"] = "qwebirc feedback from %s" % request.getclientIP()
   msg["From"] = config.feedbackengine["from"]
   msg["To"] = config.feedbackengine["to"]
   email = StringIO(msg.as_string())
   email.seek(0, 0)
   
   factorytype = SMTPSenderFactory
   factory = factorytype(fromEmail=config.feedbackengine["from"], toEmail=config.feedbackengine["to"], file=email, deferred=defer.Deferred())
   reactor.connectTCP(config.feedbackengine["smtp_host"], config.feedbackengine["smtp_port"], factory)
   self.__hit()
   return "1"
コード例 #6
0
ファイル: transport.py プロジェクト: dmaclay/vumi
    def startWorker(self):
        log.msg("Starting the SmppTransport with %s" % self.config)

        # TODO: move this to a config file
        dbindex = get_deploy_int(self._amqp_client.vhost)
        self.smpp_offset = int(self.config['smpp_offset'])
        self.transport_name = self.config.get('TRANSPORT_NAME', 'fallback')

        # Connect to Redis
        self.r_server = redis.Redis("localhost", db=dbindex)
        self.r_prefix = "%(system_id)s@%(host)s:%(port)s" % self.config
        log.msg("Connected to Redis, prefix: %s" % self.r_prefix)
        last_sequence_number = int(self.r_get_last_sequence()
                                   or self.smpp_offset)
        log.msg("Last sequence_number: %s" % last_sequence_number)

        # start the Smpp transport
        factory = EsmeTransceiverFactory(self.config,
                                            self._amqp_client.vumi_options)
        factory.loadDefaults(self.config)
        factory.setLastSequenceNumber(last_sequence_number)
        factory.setConnectCallback(self.esme_connected)
        factory.setDisconnectCallback(self.esme_disconnected)
        factory.setSubmitSMRespCallback(self.submit_sm_resp)
        factory.setDeliveryReportCallback(self.delivery_report)
        factory.setDeliverSMCallback(self.deliver_sm)
        factory.setSendFailureCallback(self.send_failure)
        log.msg(factory.defaults)
        reactor.connectTCP(
                factory.defaults['host'],
                factory.defaults['port'],
                factory)
コード例 #7
0
 def testConnectByServiceFail(self):
     try:
         reactor.connectTCP("127.0.0.1", "thisbetternotexist",
                            MyClientFactory())
     except error.ServiceNameUnknownError:
         return
     self.assert_(False, "connectTCP didn't raise ServiceNameUnknownError")
コード例 #8
0
ファイル: test_tcp.py プロジェクト: galaxysd/BitTorrent
    def testWriter(self):
        f = protocol.Factory()
        f.protocol = WriterProtocol
        f.done = 0
        f.problem = 0
        wrappedF = WiredFactory(f)
        p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
        n = p.getHost().port
        self.ports.append(p)
        clientF = WriterClientFactory()
        wrappedClientF = WiredFactory(clientF)
        reactor.connectTCP("127.0.0.1", n, wrappedClientF)

        def check(ignored):
            self.failUnless(f.done, "writer didn't finish, it probably died")
            self.failUnless(f.problem == 0, "writer indicated an error")
            self.failUnless(clientF.done,
                            "client didn't see connection dropped")
            expected = "".join(["Hello Cleveland!\n",
                                "Goodbye", " cruel", " world", "\n"])
            self.failUnless(clientF.data == expected,
                            "client didn't receive all the data it expected")
        d = defer.gatherResults([wrappedF.onDisconnect,
                                 wrappedClientF.onDisconnect])
        return d.addCallback(check)
コード例 #9
0
ファイル: test_ssl.py プロジェクト: KatiaBorges/exeLearning
    def _runTest(self, clientProto, serverProto, clientIsServer=False):
        self.clientProto = clientProto
        cf = self.clientFactory = protocol.ClientFactory()
        cf.protocol = lambda: clientProto
        if clientIsServer:
            cf.server = 0
        else:
            cf.client = 1

        self.serverProto = serverProto
        sf = self.serverFactory = protocol.ServerFactory()
        sf.protocol = lambda: serverProto
        if clientIsServer:
            sf.client = 0
        else:
            sf.server = 1

        if clientIsServer:
            inCharge = cf
        else:
            inCharge = sf
        inCharge.done = 0

        port = self.port = reactor.listenTCP(0, sf, interface="127.0.0.1")
        portNo = port.getHost().port

        reactor.connectTCP('127.0.0.1', portNo, cf)

        i = 0
        while i < 1000 and not inCharge.done:
            reactor.iterate(0.01)
            i += 1
        self.failUnless(
            inCharge.done,
            "Never finished reading all lines: %s" % (inCharge.lines,))
コード例 #10
0
ファイル: sender.py プロジェクト: NurKaynar/hacklab
def start(host='localhost', port=61613, username='******', password='******'):
    """Start twisted event loop and the fun should begin...
    """
    StompClientFactory.username = username
    StompClientFactory.password = password
    reactor.connectTCP(host, port, StompClientFactory())
    reactor.run()
コード例 #11
0
ファイル: commander.py プロジェクト: jalalhobbs/hamper
def main():
    config = hamper.config.load()
    hamper.log.setup_logging()

    reactor.connectTCP(config['server'], config['port'],
            CommanderFactory(config))
    reactor.run()
コード例 #12
0
ファイル: test_scaletix.py プロジェクト: Grindizer/scaletix
    def test_multiprocessing_factory(self):
        # Wrap the TestFactory.
        mp_factory = ScaleFactory(TestFactory(), core=2)
        # launch the new multiprocessing factory
        port = reactor.listenTCP(8118, mp_factory)

        # connect twice to the new server and check that
        # instances server run into different process'
        client_factory = TestClientFactory()
        client_factory.client_deferred_list = [Deferred(), Deferred()]
        #time.sleep(1)
        cl1 = reactor.connectTCP('localhost', 8118, client_factory)
        cl2 = reactor.connectTCP('localhost', 8118, client_factory)

        result = gatherResults(client_factory.client_deferred_list)
        def check_result(r_list):
            self.assertEqual(len(r_list), 2, "Both client should have been called. ({0})".format(repr(r_list)))
            self.assertTrue(r_list[0][0] != r_list[1][0], """pid returned from the first client should be different from
            the one returned by the second client""")

            self.assertTrue(r_list[0][1] == b'0')
            self.assertTrue(r_list[1][1] == b'1')

        result.addCallback(check_result)
        self.addCleanup(self._clean_reactor, [port], [cl1, cl2])
        return result
コード例 #13
0
ファイル: post_auth_handler.py プロジェクト: Bifrozt/honssh
    def connect_to_pot(self, returned_conn_details):
        if returned_conn_details:
            if returned_conn_details['success']:
                self.sensor_name = returned_conn_details['sensor_name']
                self.honey_ip = returned_conn_details['honey_ip']
                self.honey_port = returned_conn_details['honey_port']
                self.username = returned_conn_details['username']
                self.password = returned_conn_details['password']

                self.auth_packets = [[5, self.to_string('ssh-userauth')], [50, self.to_string(self.username) + self.to_string('ssh-connection') + self.to_string('none')]]
                
                if self.sensor_name == self.server.sensor_name and self.honey_ip == self.server.honey_ip and self.honey_port == self.server.honey_port:
                    log.msg(log.LGREEN, '[POST_AUTH]', 'Details the same as pre-auth, not re-directing')
                    self.dont_post_auth()
                else:             
                    self.server.client.loseConnection()  
                    self.server.clientConnected = False
                    if not self.server.disconnected:
                        log.msg(log.LGREEN, '[POST_AUTH]', 'Connecting to Honeypot: %s (%s:%s)' % (self.sensor_name, self.honey_ip, self.honey_port))
                        client_factory = client.HonsshClientFactory()
                        client_factory.server = self.server
                        self.bind_ip = self.server.net.setupNetworking(self.server.peer_ip, self.honey_ip, self.honey_port)
                        self.networkingSetup = True
                        reactor.connectTCP(self.honey_ip, self.honey_port, client_factory, bindAddress=(self.bind_ip, self.server.peer_port+1), timeout=10)
                        pot_connect_defer = threads.deferToThread(self.is_pot_connected)
                        pot_connect_defer.addCallback(self.pot_connected)
            else:
                log.msg(log.LBLUE, '[POST_AUTH]', 'SUCCESS = FALSE, NOT POST-AUTHING')
                self.dont_post_auth()
        else:
                log.msg(log.LRED, '[POST_AUTH][ERROR]', 'PLUGIN ERROR - DISCONNECTING ATTACKER')
                self.server.loseConnection()
コード例 #14
0
ファイル: mail.py プロジェクト: pepsiman/buildbot
    def sendmail(self, s, recipients):
        result = defer.Deferred()

        if have_ssl and self.useTls:
            client_factory = ssl.ClientContextFactory()
            client_factory.method = SSLv3_METHOD
        else:
            client_factory = None

        if self.smtpUser and self.smtpPassword:
            useAuth = True
        else:
            useAuth = False

        if not ESMTPSenderFactory:
            raise RuntimeError("twisted-mail is not installed - cannot " "send mail")
        sender_factory = ESMTPSenderFactory(
            self.smtpUser,
            self.smtpPassword,
            self.fromaddr,
            recipients,
            StringIO(s),
            result,
            contextFactory=client_factory,
            requireTransportSecurity=self.useTls,
            requireAuthentication=useAuth,
        )

        reactor.connectTCP(self.relayhost, self.smtpPort, sender_factory)

        return result
コード例 #15
0
ファイル: Metta.py プロジェクト: yhenryk/CS
	def processAT(self, data):
		try:
			timediff = data[1]
			server = data[2]
			clientID = data[3]
			location = data[4]
			time_stamp = data[5]
			#check if data exists and is the same
			if self.database.has_key(clientID):
				if time_stamp == self.database[clientID]['time_in']:
					if location == self.database[clientID]['loc_']:
						return
			#update because data is not the same
			outmsg = 'AT ' + timediff + ' ' + server + ' ' + clientID + ' ' + location + ' ' + time_stamp + '\n'
			lat, long = self._getLatLong(location)
			client_dict = {'Server_ID': server, 'time_in': time_stamp, 'loc_': location ,'at_msg': outmsg, '_lat': lat, '_long': long}
			self.database[clientID] = client_dict
			
			#send to other servers 
			self._received = outmsg
			factory = protocol.ClientFactory()
			factory.protocol = ClientProtocol
			factory.originator = self
			reactor.connectTCP('localhost', 12781, factory)
			
		except IndexError:
			outmsg = "?" + " " + data[0] + "\n"
			#self.transport.write(outmsg)
			logging.info("Command unrecognized. OUTPUT MSG: " +outmsg)
コード例 #16
0
    def render(self, request):
        """Render this request, from my server.

        This will always be asynchronous, and therefore return NOT_DONE_YET.
        It spins off a request to the pb client, and either adds it to the list
        of pending issues or requests it immediately, depending on if the
        client is already connected.
        """
        if not self.publisher:
            self.pending.append(request)
            if not self.waiting:
                self.waiting = 1
                bf = pb.PBClientFactory()
                timeout = 10
                if self.host == "unix":
                    reactor.connectUNIX(self.port, bf, timeout)
                else:
                    reactor.connectTCP(self.host, self.port, bf, timeout)
                d = bf.getRootObject()
                d.addCallbacks(self.connected, self.notConnected)

        else:
            i = Issue(request)
            self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
        return server.NOT_DONE_YET
コード例 #17
0
ファイル: build_all.py プロジェクト: clawplach/BitBlinder
def main():
  #64bit machine builds innomitor and bitblinder
#  reactor.connectTCP('192.168.1.121', 12900, SSHFactory(LinuxInnomitorBuild()))
  reactor.connectTCP('192.168.1.121', 12900, SSHFactory(LinuxBitBlinderBuild(Globals.VERSION)))
  #32bit machine just builds innomitor
#  reactor.connectTCP('192.168.1.121', 13200, SSHFactory(LinuxInnomitorBuild()))
  reactor.run()
コード例 #18
0
ファイル: session.py プロジェクト: apostolelvis/punjab
def make_session(pint, attrs, session_type='BOSH'):
    """
    pint  - punjab session interface class
    attrs - attributes sent from the body tag
    """

    s    = Session(pint, attrs)

    if pint.v:
        log.msg('================================== %s connect to %s:%s ==================================' % (str(time.time()),s.hostname,s.port))

    connect_srv = s.connect_srv
    if attrs.has_key('route'):
        connect_srv = False
    if s.hostname in ['localhost', '127.0.0.1']:
        connect_srv = False
    if not connect_srv:
        reactor.connectTCP(s.hostname, s.port, s, bindAddress=pint.bindAddress)
    else:
        connector = XMPPClientConnector(reactor, s.hostname, s)
        connector.connect()
    # timeout
    reactor.callLater(s.inactivity, s.checkExpired)

    pint.sessions[s.sid] = s

    return s, s.waiting_requests[0].deferred
コード例 #19
0
ファイル: ncidmon.py プロジェクト: shrick/ncidmon
def main():
    # command line processing
    process_commandline()

    call_list_server = None
    # run the call list providing web server in listening mode
    if CONFIG["LISTEN"]:
        call_list_server = CallListServer()
        site = http_server.Site(call_list_server)
        try:
            reactor.listenTCP(CONFIG["HTTP_PORT"], site, interface=CONFIG["HTTP_HOST"])
        except:
            # port could not be bound
            # (already in use, permission denied, ...)
            call_list_server = None
        else:
            dprint("running call list web server on 'http://{HTTP_HOST}:{HTTP_PORT}'".format(**CONFIG))

    # configure notifications
    enable_notifcations(
        not CONFIG["DISABLE_NOTIFICATIONS"],
        # 'All recent calls...' link only when the call list webserver
        # is running
        call_list_server,
    )

    # start the client
    reactor.connectTCP(
        CONFIG["NCID_HOST"], CONFIG["NCID_PORT"], NCIDClientFactory(reactor, CONFIG["LISTEN"], call_list_server)
    )

    # run the event dispatcher
    reactor.run()

    dprint("done.")
コード例 #20
0
ファイル: proxyclient.py プロジェクト: GNOME/postr
 def handleStatus_301(self):
     l = self.headers.get('location')
     if not l:
         self.handleStatusDefault()
         return
     url = l[0]
     if self.followRedirect:
         scheme, host, port, path = \
             _parse(url, defaultPort=self.transport.getPeer().port)
         self.factory.setURL(url)
 
         if self.factory.scheme == 'https':
             from twisted.internet import ssl
             contextFactory = ssl.ClientContextFactory()
             reactor.connectSSL(self.factory.host, self.factory.port, 
                                self.factory, contextFactory)
         else:
             reactor.connectTCP(self.factory.host, self.factory.port, 
                                self.factory)
     else:
         self.handleStatusDefault()
         self.factory.noPage(
             failure.Failure(
                 error.PageRedirect(
                     self.status, self.message, location = url)))
     self.quietLoss = 1
     self.transport.loseConnection()
コード例 #21
0
ファイル: karmabot.py プロジェクト: drd/karmabot
def main():
    from optparse import OptionParser
    parser = OptionParser(usage="usage: %prog [options] channels")

    # IRC connection options
    parser.add_option("-s", "--server",
                      action="store", dest="server",
                      default="irc.freenode.net",
                      help="IRC server to connect to")
    parser.add_option("-p", "--port",
                      action="store", type="int", dest="port", default=None,
                      help="IRC server to connect to")
    parser.add_option("--ssl",
                      action="store_true", dest="ssl", default=False,
                      help="use SSL")
    parser.add_option("--password",
                      action="store", dest="password", default=None,
                      help="server password")
    parser.add_option("-n", "--nick",
                      action="store", dest="nick", default="karmabot",
                      help="nickname to use")
    # Bot options
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="enable verbose output")
    parser.add_option("-d", "--data",
                      action="store", dest="filename", default="karma.json",
                      help="karma data file name")
    parser.add_option("-t", "--trust",
                      action="append", dest="trusted", default=[],
                      help="trusted hostmasks")
    parser.add_option("-f", "--facets",
                      action="append", dest="facets", default=[],
                      help="additional facets to load")

    (options, channels) = parser.parse_args()

    if not channels:
        parser.error("You must supply some channels to join.")
    else:
        log.msg("Channels to join: %s" % channels)

    if options.verbose:
        log.startLogging(sys.stdout)

    if not options.port:
        options.port = 6667 if not options.ssl else 9999
    
    # FIXME: this needs to be replaced with a real facet manager
    for facet_path in options.facets:
        execfile(facet_path, globals())

    factory = KarmaBotFactory(options.filename, options.nick,
                              channels, options.trusted, options.password)
    if not options.ssl:
        reactor.connectTCP(options.server, options.port, factory)
    else:
        reactor.connectSSL(options.server, options.port,
                           factory, ssl.ClientContextFactory())
    reactor.run()
コード例 #22
0
 def start(self):
     f = pb.PBClientFactory()
     d = f.login(credentials.UsernamePassword('local1', 'localpw'), self)
     reactor.connectTCP('127.0.0.1', self.port, f)
     # we need to hold a reference to this, otherwise the broker will sever
     # the connection
     self.mind = yield d
コード例 #23
0
ファイル: redisapi.py プロジェクト: drednout/redis_vs_mysql
 def connect(self):
     factory = RedisClientFactory(password=self.password, db=self.db, use_hiredis=self.use_hiredis)
     reactor.connectTCP(self.host, self.port, factory)
     self.redis_conn, new_defer = yield factory.deferred
     logging.debug("self.redis_conn is %s" % str(self.redis_conn))
     setattr(self.factory, self.factory_attr, self.redis_conn)
     new_defer.addCallback(self.reconnect_callback)
コード例 #24
0
ファイル: tryclient.py プロジェクト: ahussein/buildbot
    def deliverJob(self):
        # returns a Deferred that fires when the job has been delivered

        if self.connect == "ssh":
            tryhost = self.getopt("tryhost")
            tryuser = self.getopt("username")
            trydir = self.getopt("trydir")

            argv = ["ssh", "-l", tryuser, tryhost, "buildbot", "tryserver", "--jobdir", trydir]
            # now run this command and feed the contents of 'job' into stdin

            pp = RemoteTryPP(self.jobfile)
            reactor.spawnProcess(pp, argv[0], argv, os.environ)
            d = pp.d
            return d
        if self.connect == "pb":
            user = self.getopt("username")
            passwd = self.getopt("passwd")
            master = self.getopt("master")
            tryhost, tryport = master.split(":")
            tryport = int(tryport)
            f = pb.PBClientFactory()
            d = f.login(credentials.UsernamePassword(user, passwd))
            reactor.connectTCP(tryhost, tryport, f)
            d.addCallback(self._deliverJob_pb)
            return d
        raise RuntimeError("unknown connecttype '%s', should be 'ssh' or 'pb'" % self.connect)
コード例 #25
0
ファイル: tryclient.py プロジェクト: ahussein/buildbot
 def getStatus(self):
     # returns a Deferred that fires when the builds have finished, and
     # may emit status messages while we wait
     wait = bool(self.getopt("wait", "try_wait"))
     if not wait:
         # TODO: emit the URL where they can follow the builds. This
         # requires contacting the Status server over PB and doing
         # getURLForThing() on the BuildSetStatus. To get URLs for
         # individual builds would require we wait for the builds to
         # start.
         print "not waiting for builds to finish"
         return
     d = self.running = defer.Deferred()
     if self.buildsetStatus:
         self._getStatus_1()
         return self.running
     # contact the status port
     # we're probably using the ssh style
     master = self.getopt("master")
     host, port = master.split(":")
     port = int(port)
     self.announce("contacting the status port at %s:%d" % (host, port))
     f = pb.PBClientFactory()
     creds = credentials.UsernamePassword("statusClient", "clientpw")
     d = f.login(creds)
     reactor.connectTCP(host, port, f)
     d.addCallback(self._getStatus_ssh_1)
     return self.running
コード例 #26
0
ファイル: DownloadFiles.py プロジェクト: jredrejo/controlaula
 def addRequest(self, uri, file,exitfunc):
     self.exitfunc=exitfunc
     if len(self.deferreds) >= self.SIZE:
         # wait for completion of all previous requests
         DeferredList(self.deferreds
         ).addCallback(self._callback)
         self.deferreds = []
         
         # queue the request
         deferred = Deferred()
         self.requests.append((uri, file,deferred))
         
         return deferred
     else:
         # execute the request now
         #deferred = downloadPage(url, file)
         host, port, url = MyUtils.parse(uri)
         f = client.HTTPDownloader(uri, file)
         f.deferred.addCallbacks(callback=self.exitfunc,
                             callbackArgs=(file,) )
                 
         self.deferreds.append(f.deferred)
         reactor.connectTCP(host, port, f)
         
         return f.deferred
コード例 #27
0
    def testWriteLimit(self):
        server = Server()
        c1, c2 = SimpleProtocol(), SimpleProtocol()

        # The throttling factory starts checking bandwidth immediately
        now = time.time()

        tServer = policies.ThrottlingFactory(server, writeLimit=10)
        port = reactor.listenTCP(0, tServer, interface="127.0.0.1")
        n = port.getHost()[2]
        reactor.iterate(); reactor.iterate()
        for c in c1, c2:
            reactor.connectTCP("127.0.0.1", n, SillyFactory(c))
            self.doIterations()

        for p in tServer.protocols.keys():
            p = p.wrappedProtocol
            self.assert_(isinstance(p, EchoProtocol))
            p.transport.registerProducer(p, 1)

        c1.transport.write("0123456789")
        c2.transport.write("abcdefghij")
        self.doIterations()

        self.assertEquals(c1.buffer, "0123456789")
        self.assertEquals(c2.buffer, "abcdefghij")
        self.assertEquals(tServer.writtenThisSecond, 20)

        # at this point server should've written 20 bytes, 10 bytes
        # above the limit so writing should be paused around 1 second
        # from 'now', and resumed a second after that

        for p in tServer.protocols.keys():
            self.assert_(not hasattr(p.wrappedProtocol, "paused"))
            self.assert_(not hasattr(p.wrappedProtocol, "resume"))

        while not hasattr(p.wrappedProtocol, "paused"):
            reactor.iterate()

        self.assertEquals(tServer.writtenThisSecond, 0)

        for p in tServer.protocols.keys():
            self.assert_(hasattr(p.wrappedProtocol, "paused"))
            self.assert_(not hasattr(p.wrappedProtocol, "resume"))
            self.assert_(abs(p.wrappedProtocol.paused - now - 1.0) < 0.1)

        while not hasattr(p.wrappedProtocol, "resume"):
            reactor.iterate()

        for p in tServer.protocols.keys():
            self.assert_(hasattr(p.wrappedProtocol, "resume"))
            self.assert_(abs(p.wrappedProtocol.resume -
                             p.wrappedProtocol.paused - 1.0) < 0.1)

        c1.transport.loseConnection()
        c2.transport.loseConnection()
        port.stopListening()
        for p in tServer.protocols.keys():
            p.loseConnection()
        self.doIterations()
コード例 #28
0
ファイル: bar_daemon.py プロジェクト: 0rbytal/BAR
 def received_broadcast(self, data):
         print "Received feed."
         message = Message(data)
         row = db.select_entries("contacts", {"label": message.label})
         if len(row) == 0:
             print "Can't find this label: " + message.label
             return
         row = row[0]
         message.decrypt(row["sharedkey"])
         if not message.validate():
             print "Received an invalid message."
             return
         print "Found label: " + message.label
         if self.factory.role == "hidden-client":
             if self.factory.listener_factory:
                 self.factory.listener_factory.send_message(message.cleartext_msg)
                 self.factory.listener_factory.client.transport.loseConnection()
                 db.insert_entry("contacts", {"name": self.factory.name, "label":message.new_label, "sharedkey": row["sharedkey"]})
         else:
             if self.factory.role == "proxy":
                 message.cleartext_msg = re.sub(r'CONNECT (?P<value>.*?) HTTP/1.0\r\n', 'CONNECT localhost HTTP/1.0\r\n', message.cleartext_msg)
             socks_client_factory = HTTPClientFactory(reactor, message)
             socks_client_factory.set_communicator(self)
             reactor.connectTCP("localhost", 4333, socks_client_factory)
             db.insert_entry("contacts", {"name": self.factory.name, "label":message.new_label, "sharedkey": row["sharedkey"]})
コード例 #29
0
 def is_already_running(self):
     """Check if the instance is already running."""
     factory = PortDetectFactory()
     # pylint: disable=E1101
     reactor.connectTCP(LOCALHOST, self.config.port, factory)
     result = yield factory.is_listening()
     defer.returnValue(result)
コード例 #30
0
ファイル: proxyclient.py プロジェクト: GNOME/postr
def _makeDeferredRequest(url, contextFactory=None, proxy=None,
                         progress_tracker=None,
                         clientFactoryClass=None,
                         *args, **kwargs):
    """Download a web page as a string.

    Download a page. Return a deferred, which will callback with a
    page (as a string) or errback with a description of the error.

    See HTTPClientFactory to see what extra args can be passed.
    """
    if proxy:
        scheme, host, port, path = _parse(proxy)
        kwargs['proxy'] = proxy
    else:
        scheme, host, port, path = _parse(url)

    if not clientFactoryClass:
        clientFactoryClass = HTTPClientFactory
    factory = clientFactoryClass(url, *args, **kwargs)

    if progress_tracker is not None and hasattr(factory, 'set_progress_tracker'):
        factory.set_progress_tracker(progress_tracker)

    if scheme == 'https':
        from twisted.internet import ssl
        if contextFactory is None:
            contextFactory = ssl.ClientContextFactory()
        reactor.connectSSL(host, port, factory, contextFactory)
    else:
        reactor.connectTCP(host, port, factory)
    return factory.deferred
コード例 #31
0
ファイル: main.py プロジェクト: MobiusL/p2pool
def main(args, net, datadir_path, merged_urls, worker_endpoint):
    try:
        print 'p2pool (version %s)' % (p2pool.__version__, )
        print

        @defer.inlineCallbacks
        def connect_p2p():
            # connect to bitcoind over bitcoin-p2p
            print '''Testing bitcoind P2P connection to '%s:%s'...''' % (
                args.bitcoind_address, args.bitcoind_p2p_port)
            factory = bitcoin_p2p.ClientFactory(net.PARENT)
            reactor.connectTCP(args.bitcoind_address, args.bitcoind_p2p_port,
                               factory)
            yield factory.getProtocol()  # waits until handshake is successful
            print '    ...success!'
            print
            defer.returnValue(factory)

        if args.testnet:  # establish p2p connection first if testnet so bitcoind can work without connections
            factory = yield connect_p2p()

        # connect to bitcoind over JSON-RPC and do initial getmemorypool
        url = '%s://%s:%i/' % ('https' if args.bitcoind_rpc_ssl else 'http',
                               args.bitcoind_address, args.bitcoind_rpc_port)
        print '''Testing bitcoind RPC connection to '%s' with username '%s'...''' % (
            url, args.bitcoind_rpc_username)
        bitcoind = jsonrpc.Proxy(
            url,
            dict(Authorization='Basic ' +
                 base64.b64encode(args.bitcoind_rpc_username + ':' +
                                  args.bitcoind_rpc_password)),
            timeout=30)
        yield helper.check(bitcoind, net)
        temp_work = yield helper.getwork(bitcoind)

        bitcoind_warning_var = variable.Variable(None)

        @defer.inlineCallbacks
        def poll_warnings():
            errors = (yield
                      deferral.retry('Error while calling getmininginfo:')(
                          bitcoind.rpc_getmininginfo)())['errors']
            bitcoind_warning_var.set(errors if errors != '' else None)

        yield poll_warnings()
        task.LoopingCall(poll_warnings).start(20 * 60)

        print '    ...success!'
        print '    Current block hash: %x' % (temp_work['previous_block'], )
        print '    Current block height: %i' % (temp_work['height'] - 1, )
        print

        if not args.testnet:
            factory = yield connect_p2p()

        print 'Determining payout address...'
        if args.pubkey_hash is None:
            address_path = os.path.join(datadir_path, 'cached_payout_address')

            if os.path.exists(address_path):
                with open(address_path, 'rb') as f:
                    address = f.read().strip('\r\n')
                print '    Loaded cached address: %s...' % (address, )
            else:
                address = None

            if address is not None:
                res = yield deferral.retry(
                    'Error validating cached address:',
                    5)(lambda: bitcoind.rpc_validateaddress(address))()
                if not res['isvalid'] or not res['ismine']:
                    print '    Cached address is either invalid or not controlled by local bitcoind!'
                    address = None

            if address is None:
                print '    Getting payout address from bitcoind...'
                address = yield deferral.retry(
                    'Error getting payout address from bitcoind:',
                    5)(lambda: bitcoind.rpc_getaccountaddress('p2pool'))()

            with open(address_path, 'wb') as f:
                f.write(address)

            my_pubkey_hash = bitcoin_data.address_to_pubkey_hash(
                address, net.PARENT)
        else:
            my_pubkey_hash = args.pubkey_hash
        print '    ...success! Payout address:', bitcoin_data.pubkey_hash_to_address(
            my_pubkey_hash, net.PARENT)
        print

        ss = p2pool_data.ShareStore(os.path.join(datadir_path, 'shares.'), net)
        shares = {}
        known_verified = set()
        print "Loading shares..."
        for i, (mode, contents) in enumerate(ss.get_shares()):
            if mode == 'share':
                contents.time_seen = 0
                shares[contents.hash] = contents
                if len(shares) % 1000 == 0 and shares:
                    print "    %i" % (len(shares), )
            elif mode == 'verified_hash':
                known_verified.add(contents)
            else:
                raise AssertionError()
        print "    ...done loading %i shares (%i verified)!" % (
            len(shares), len(known_verified))
        print

        print 'Initializing work...'

        node = p2pool_node.Node(factory, bitcoind, shares.values(),
                                known_verified, net)
        yield node.start()

        for share_hash in shares:
            if share_hash not in node.tracker.items:
                ss.forget_share(share_hash)
        for share_hash in known_verified:
            if share_hash not in node.tracker.verified.items:
                ss.forget_verified_share(share_hash)
        del shares, known_verified
        node.tracker.removed.watch(lambda share: ss.forget_share(share.hash))
        node.tracker.verified.removed.watch(
            lambda share: ss.forget_verified_share(share.hash))

        def save_shares():
            for share in node.tracker.get_chain(
                    node.best_share_var.value,
                    min(node.tracker.get_height(node.best_share_var.value),
                        2 * net.CHAIN_LENGTH)):
                ss.add_share(share)
                if share.hash in node.tracker.verified.items:
                    ss.add_verified_hash(share.hash)

        task.LoopingCall(save_shares).start(60)

        print '    ...success!'
        print

        print 'Joining p2pool network using port %i...' % (args.p2pool_port, )

        @defer.inlineCallbacks
        def parse(x):
            if ':' in x:
                ip, port = x.split(':')
                defer.returnValue(((yield reactor.resolve(ip)), int(port)))
            else:
                defer.returnValue(((yield reactor.resolve(x)), net.P2P_PORT))

        addrs = {}
        if os.path.exists(os.path.join(datadir_path, 'addrs')):
            try:
                with open(os.path.join(datadir_path, 'addrs'), 'rb') as f:
                    addrs.update(
                        dict((tuple(k), v) for k, v in json.loads(f.read())))
            except:
                print >> sys.stderr, 'error parsing addrs'
        for addr_df in map(parse, net.BOOTSTRAP_ADDRS):
            try:
                addr = yield addr_df
                if addr not in addrs:
                    addrs[addr] = (0, time.time(), time.time())
            except:
                log.err()

        connect_addrs = set()
        for addr_df in map(parse, args.p2pool_nodes):
            try:
                connect_addrs.add((yield addr_df))
            except:
                log.err()

        node.p2p_node = p2pool_node.P2PNode(
            node,
            port=args.p2pool_port,
            max_incoming_conns=args.p2pool_conns,
            addr_store=addrs,
            connect_addrs=connect_addrs,
            desired_outgoing_conns=args.p2pool_outgoing_conns,
        )
        node.p2p_node.start()

        def save_addrs():
            with open(os.path.join(datadir_path, 'addrs'), 'wb') as f:
                f.write(json.dumps(node.p2p_node.addr_store.items()))

        task.LoopingCall(save_addrs).start(60)

        print '    ...success!'
        print

        if args.upnp:

            @defer.inlineCallbacks
            def upnp_thread():
                while True:
                    try:
                        is_lan, lan_ip = yield ipdiscover.get_local_ip()
                        if is_lan:
                            pm = yield portmapper.get_port_mapper()
                            yield pm._upnp.add_port_mapping(
                                lan_ip, args.p2pool_port, args.p2pool_port,
                                'p2pool', 'TCP')
                    except defer.TimeoutError:
                        pass
                    except:
                        if p2pool.DEBUG:
                            log.err(None, 'UPnP error:')
                    yield deferral.sleep(random.expovariate(1 / 120))

            upnp_thread()

        # start listening for workers with a JSON-RPC server

        print 'Listening for workers on %r port %i...' % (worker_endpoint[0],
                                                          worker_endpoint[1])

        wb = work.WorkerBridge(node, my_pubkey_hash, args.donation_percentage,
                               merged_urls, args.worker_fee)
        web_root = web.get_web_root(wb, datadir_path, bitcoind_warning_var)
        worker_interface.WorkerInterface(wb).attach_to(
            web_root, get_handler=lambda request: request.redirect('/static/'))

        deferral.retry('Error binding to worker port:', traceback=False)(
            reactor.listenTCP)(worker_endpoint[1],
                               server.Site(web_root),
                               interface=worker_endpoint[0])

        with open(os.path.join(os.path.join(datadir_path, 'ready_flag')),
                  'wb') as f:
            pass

        print '    ...success!'
        print

        # done!
        print 'Started successfully!'
        print 'Go to http://127.0.0.1:%i/ to view graphs and statistics!' % (
            worker_endpoint[1], )
        if args.donation_percentage > 0.51:
            print '''Donating %.1f%% of work towards P2Pool's development. Thanks for the tip!''' % (
                args.donation_percentage, )
        elif args.donation_percentage < 0.49:
            print '''Donating %.1f%% of work towards P2Pool's development. Please donate to encourage further development of P2Pool!''' % (
                args.donation_percentage, )
        else:
            print '''Donating %.1f%% of work towards P2Pool's development. Thank you!''' % (
                args.donation_percentage, )
            print 'You can increase this amount with --give-author argument! (or decrease it, if you must)'
        print

        if hasattr(signal, 'SIGALRM'):
            signal.signal(
                signal.SIGALRM, lambda signum, frame: reactor.callFromThread(
                    sys.stderr.write, 'Watchdog timer went off at:\n' + ''.
                    join(traceback.format_stack())))
            signal.siginterrupt(signal.SIGALRM, False)
            task.LoopingCall(signal.alarm, 30).start(1)

        if args.irc_announce:
            from twisted.words.protocols import irc

            class IRCClient(irc.IRCClient):
                nickname = 'p2pool%02i' % (random.randrange(100), )
                channel = net.ANNOUNCE_CHANNEL

                def lineReceived(self, line):
                    if p2pool.DEBUG:
                        print repr(line)
                    irc.IRCClient.lineReceived(self, line)

                def signedOn(self):
                    self.in_channel = False
                    irc.IRCClient.signedOn(self)
                    self.factory.resetDelay()
                    self.join(self.channel)

                    @defer.inlineCallbacks
                    def new_share(share):
                        if not self.in_channel:
                            return
                        if share.pow_hash <= share.header[
                                'bits'].target and abs(share.timestamp -
                                                       time.time()) < 10 * 60:
                            yield deferral.sleep(random.expovariate(1 / 60))
                            message = '\x02%s BLOCK FOUND by %s! %s%064x' % (
                                net.NAME.upper(),
                                bitcoin_data.script2_to_address(
                                    share.new_script, net.PARENT),
                                net.PARENT.BLOCK_EXPLORER_URL_PREFIX,
                                share.header_hash)
                            if all('%x' %
                                   (share.header_hash, ) not in old_message
                                   for old_message in self.recent_messages):
                                self.say(self.channel, message)
                                self._remember_message(message)

                    self.watch_id = node.tracker.verified.added.watch(
                        new_share)
                    self.recent_messages = []

                def joined(self, channel):
                    self.in_channel = True

                def left(self, channel):
                    self.in_channel = False

                def _remember_message(self, message):
                    self.recent_messages.append(message)
                    while len(self.recent_messages) > 100:
                        self.recent_messages.pop(0)

                def privmsg(self, user, channel, message):
                    if channel == self.channel:
                        self._remember_message(message)

                def connectionLost(self, reason):
                    node.tracker.verified.added.unwatch(self.watch_id)
                    print 'IRC connection lost:', reason.getErrorMessage()

            class IRCClientFactory(protocol.ReconnectingClientFactory):
                protocol = IRCClient

            reactor.connectTCP("irc.freenode.net", 6667, IRCClientFactory())

        @defer.inlineCallbacks
        def status_thread():
            last_str = None
            last_time = 0
            while True:
                yield deferral.sleep(3)
                try:
                    height = node.tracker.get_height(node.best_share_var.value)
                    this_str = 'P2Pool: %i shares in chain (%i verified/%i total) Peers: %i (%i incoming)' % (
                        height,
                        len(node.tracker.verified.items),
                        len(node.tracker.items),
                        len(node.p2p_node.peers),
                        sum(1 for peer in node.p2p_node.peers.itervalues()
                            if peer.incoming),
                    ) + (' FDs: %i R/%i W' %
                         (len(reactor.getReaders()), len(reactor.getWriters()))
                         if p2pool.DEBUG else '')

                    datums, dt = wb.local_rate_monitor.get_datums_in_last()
                    my_att_s = sum(datum['work'] / dt for datum in datums)
                    this_str += '\n Local: %sH/s in last %s Local dead on arrival: %s Expected time to share: %s' % (
                        math.format(int(my_att_s)),
                        math.format_dt(dt),
                        math.format_binomial_conf(
                            sum(1 for datum in datums if datum['dead']),
                            len(datums), 0.95),
                        math.format_dt(2**256 / node.tracker.items[
                            node.best_share_var.value].max_target / my_att_s)
                        if my_att_s and node.best_share_var.value else '???',
                    )

                    if height > 2:
                        (stale_orphan_shares,
                         stale_doa_shares), shares, _ = wb.get_stale_counts()
                        stale_prop = p2pool_data.get_average_stale_prop(
                            node.tracker, node.best_share_var.value,
                            min(60 * 60 // net.SHARE_PERIOD, height))
                        real_att_s = p2pool_data.get_pool_attempts_per_second(
                            node.tracker, node.best_share_var.value,
                            min(height - 1, 60 * 60 //
                                net.SHARE_PERIOD)) / (1 - stale_prop)

                        this_str += '\n Shares: %i (%i orphan, %i dead) Stale rate: %s Efficiency: %s Current payout: %.4f %s' % (
                            shares,
                            stale_orphan_shares,
                            stale_doa_shares,
                            math.format_binomial_conf(
                                stale_orphan_shares + stale_doa_shares, shares,
                                0.95),
                            math.format_binomial_conf(
                                stale_orphan_shares + stale_doa_shares, shares,
                                0.95, lambda x: (1 - x) / (1 - stale_prop)),
                            node.get_current_txouts().get(
                                bitcoin_data.pubkey_hash_to_script2(
                                    my_pubkey_hash), 0) * 1e-8,
                            net.PARENT.SYMBOL,
                        )
                        this_str += '\n Pool: %sH/s Stale rate: %.1f%% Expected time to block: %s' % (
                            math.format(int(real_att_s)),
                            100 * stale_prop,
                            math.format_dt(
                                2**256 /
                                node.bitcoind_work.value['bits'].target /
                                real_att_s),
                        )

                        for warning in p2pool_data.get_warnings(
                                node.tracker, node.best_share_var.value, net,
                                bitcoind_warning_var.value,
                                node.bitcoind_work.value):
                            print >> sys.stderr, '#' * 40
                            print >> sys.stderr, '>>> Warning: ' + warning
                            print >> sys.stderr, '#' * 40

                    if this_str != last_str or time.time() > last_time + 15:
                        print this_str
                        last_str = this_str
                        last_time = time.time()
                except:
                    log.err()

        status_thread()
    except:
        reactor.stop()
        log.err(None, 'Fatal error:')
コード例 #32
0
        else:
            if len(self.searchText) == self.cols - 2: return
            self.searchText = self.searchText + chr(c)

        self.stdscr.addstr(
            self.rows - 1, 0,
            self.searchText + (' ' * (self.cols - len(self.searchText) - 2)))
        self.stdscr.move(self.rows - 1, len(self.searchText))
        self.paintStatus(self.statusText + ' %d' % len(self.searchText))
        self.stdscr.refresh()

    def close(self):
        """ clean up """

        curses.nocbreak()
        self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()


if __name__ == '__main__':
    stdscr = curses.initscr()  # initialize curses
    screen = Screen(stdscr)  # create Screen object
    stdscr.refresh()
    ircFactory = IRCFactory(screen)
    reactor.addReader(screen)  # add screen object as a reader to the reactor
    reactor.connectTCP("irc.freenode.net", 6667, ircFactory)  # connect to IRC
    reactor.run()  # have fun!
    screen.close()
コード例 #33
0
class SerialD():
     cuenta=0
     def __init__(self):
          self.datos=None;
          self.ser_acm0 = serial.Serial()
          self.ser_acm0.baudrate = 115200
          self.ser_acm0.port = '/dev/ttyACM0'
          self.sensores=[0,0,0,0,0]
          
     def start(self):
            try:
                self.ser_acm0.open()
            except:
                self.ser_acm0.port='/dev/ttyUSB0'
                self.ser_acm0.open()
            self.hilo=threading.Thread(target=self.update, args=())
            self.hilo.start()
          
     def end(self):
          self.ser_acm0.close()
          
     def update(self):
        while self.ser_acm0.isOpen():
            self.ser_acm0.flush() #espera a  exista un dato
            datos=self.ser_acm0.readline()
            if (datos.decode('cp1250').replace('\r\n','')=='a'):

            time.sleep(0.1)
            
                          
     def press(self,key):
         #print(key.encode('cp1250'))
         self.ser_acm0.write(key.encode('cp1250'))#codifica y envia
       


class AppProtocol(WebSocketClientProtocol):    
    def onOpen(self):
        self.seri=SerialD()
        print("Abierto")

    def onConnect(self, response):
        print("server conectado")

    def onConnecting(self, transport_details):
        print("Conectando")
        return None  # ask for defaults

    def onMessage(self, payload, isBinary):
        text_data_json = json.loads(payload.decode('utf8'))
        if(text_data_json['type']=='MC'):
                print("MC")
                self.seri.start()
                self._loop = LoopingCall(self.envioSerial)
                self._loop.start(0.1)
               
        elif(text_data_json['type']=='MD'):
                subprocess.call('/usr/bin/pm2 restart 0',shell=True)
                print("MD")
        else:
            message = text_data_json['message']
            print(message)
            self.seri.press(str(message))

    def onClose(self, wasClean, code, reason): 
        print("WebSocket connection closed")
        
    def envioSerial(self):
        self.sendMessage(json.dumps({'userFrom':'2','userTo': '1','type':'sensores','message':self.seri.sensores}).encode('utf8'))
        
        
        
class AppFactory(WebSocketClientFactory, ReconnectingClientFactory):
    protocol = AppProtocol

    def clientConnectionFailed(self, connector, reason):
        print("Unable connect to the server")
        self.retry(connector)
        subprocess.call('/usr/bin/pm2 restart 0',shell=True)

    def clientConnectionLost(self, connector, reason):
        print("Lost connection and retrying...")
        self.retry(connector)
        subprocess.call('/usr/bin/pm2 restart 0',shell=True)


if __name__ == '__main__':
    
    from twisted.python import log
    from twisted.internet import reactor
    log.startLogging(sys.stdout)
    factory = AppFactory(u"ws://ritaportal.udistrital.edu.co:10207/jordan")
    reactor.connectTCP(server, port, factory)
    reactor.run()
コード例 #34
0
def gnutella_connect(port, ip):
    for i in range(0, 100):
        if i != port:
            reactor.connectTCP("127.0.0.1", 8000 + i,
                               Sender.GnutellaFactory(True))
コード例 #35
0
 def connectTCP(self, *arg, **kw):
     return reactor.connectTCP(*arg,
                               bindAddress=(network_interface.get(), 0),
                               **kw)
コード例 #36
0
ファイル: teste.py プロジェクト: Brunovf1/pade-1
# -*- coding: utf-8 -*-

from twisted.internet import protocol, reactor


class Echo(protocol.Protocol):
    def connectionMade(self):
        self.transport.write('Hello Server!')
        print 'Connection established!'

    def dataReceived(self, data):
        print data


class EchoFactory(protocol.ClientFactory):
    def buildProtocol(self, addr):
        return Echo()

    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed!'
        print reason.getErrorMessage()
        reactor.stop()


if __name__ == '__main__':
    print 'Connecting...'
    reactor.connectTCP('192.168.0.32', 1234, EchoFactory())
    reactor.run()
コード例 #37
0
from twisted.internet import protocol, reactor

HOST = 'localhost'
PORT = 21567

class TSClntProtocol(protocol.Protocol):
    def sendDate(self):
        data = input('> ')
        if data:
            print('...sending %s...'%data)
            self.transport.write(data)
        else:
            self.transport.loseConnection()

    def connectionMade(self):
        self.sendDate()

    def dataReceived(self, data):
        print(data)
        self.sendDate()

class TSClntFactory(protocol.ClientFactory):
    protocol = TSClntProtocol
    clientConnectionLost = clientConnectionFailed = \
        lambda self, connector, reason: reactor.stop()

reactor.connectTCP(HOST, PORT, TSClntFactory())
reactor.run()
コード例 #38
0
ファイル: main.py プロジェクト: kzerot/RandomAdventurer
        self.transport.write(data)


class GameClientFactory(ClientFactory):
    def __init__(self, world):
        self.world = world

    def startedConnecting(self, connector):
        print 'Started to connect.'

    def buildProtocol(self, addr):
        print 'Connected.'
        return GameClient(self, self.world)

    def clientConnectionLost(self, connector, reason):
        print 'Lost connection.  Reason:', reason
        # connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason


w = World(reactor, isServer)

if isServer:
    reactor.listenTCP(8123, ServerFactory(w))
else:
    reactor.connectTCP('localhost', 8123, GameClientFactory(w))

LoopingCall(w.taskMgr.step).start(1 / 60)
reactor.run()
コード例 #39
0
            password = arg

    #create application
    app = QtWidgets.QApplication(sys.argv)

    #add qt4 reactor

    try:
        import qt5reactor
        qt5reactor.install()
    except:
        if "twisted.internet.reactor" in sys.modules:
            del sys.modules["twisted.internet.reactor"]
        import qt5reactor
        qt5reactor.install()

    from twisted.internet import reactor

    for arg in args:
        if ':' in arg:
            ip, port = arg.split(':')
        else:
            ip, port = arg, "5900"

        reactor.connectTCP(
            ip, int(port), RFBScreenShotFactory(password,
                                                path + "%s.jpg" % ip))

    reactor.runReturn()
    app.exec_()
コード例 #40
0
class botFactory(protocol.ClientFactory):
    global conf_file

    def __init__(self):
        self.config = Config(conf_file)

    def buildProtocol(self, addr):
        p = bot(self.config)
        p.factory = self
        return p

    def clientConnectionLost(self, connector, reason):
        print "Connection lost. Reconnecting..."
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print "connection failed:", reason
        reactor.stop()


if __name__ == '__main__':

    print "Starting Pybot Version: " + str(version)
    f = botFactory()

    reactor.connectTCP(network, port, f)

    print "Connecting..."

    reactor.run()
コード例 #41
0
 def connect(self):
     factory = pb.PBClientFactory()
     reactor.connectTCP("localhost", 8789, factory)
     return factory.login(self.credentials).addCallback(self._connected)
コード例 #42
0
    def connect(self):
        tronHost = self.actor.actorConfig['tron']['host']
        tronPort = self.actor.actorConfig['tron']['cmdrPort']

        reactor.connectTCP(tronHost, tronPort, self.connector)
コード例 #43
0
            print "Writing message", key
            i = value[0].index('BODY') + 2
            msg = email.message_from_string(value[0][i])
            destfd.write(msg.as_string(unixfrom=1))
            destfd.write("\n")
        self.uidlist.add(int(uid))

    def deletemessages(self, data=None):
        print "Deleting messages", str(self.uidlist)
        d = self.proto.addFlags(str(self.uidlist), ["\\Deleted"], uid=1)
        d.addCallback(lambda x: self.proto.expunge())
        return d

    def logout(self, data=None):
        return self.proto.logout()

    def stopreactor(self, data=None):
        reactor.stop()

    def errorhappened(self, failure):
        print "An error occured:", failure.getErrorMessage()
        d = self.logout()
        d.addBoth(self.stopreactor)
        return failure


print "WARNING: this program will delete all mail from the INBOX!"
password = getpass.getpass("Enter password for %s on %s: " % \
                           (sys.argv[2], sys.argv[1]))
reactor.connectTCP(sys.argv[1], 143, IMAPFactory(sys.argv[2], password))
reactor.run()
コード例 #44
0
 def connectTCP(self, *arg, **kw):
     return reactor.connectTCP(*arg,
                               bindAddress=(self.config.get(
                                   'network_interface', ''), 0),
                               **kw)
コード例 #45
0
 def initiateFileTransfer(self, filename, port):
     log.debug('Downloading {} from port {}'.format(filename, port))
     filepath = os.path.join(self.output_directory, filename)
     session = FileReceiverFactory(filepath, self)
     connector = reactor.connectTCP(self.config.host, port, session)
     self.transfers_in_progress[session] = connector
コード例 #46
0
 def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs):
     scheme, host, port, path = client._parse(url)
     self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs)
     self.connection = reactor.connectTCP(host, port, self.factory)
コード例 #47
0
                self.transport.abortConnection()
                return

        self.send_outgoing_data()
        if close_connection:
            self.transport.loseConnection()

    def send_outgoing_data(self):
        # This is more complicated than it should because we want to print all outgoing data here.
        # Normally, self.transport.write(self.conn.data_to_send()) would suffice.
        output = self.conn.data_to_send()
        if output:
            print('>>> ' + output.decode('utf-8').replace('\r\n', '\r\n>>> ').rstrip('> \r\n'))
            self.transport.write(output)


class IRCClientFactory(ClientFactory):
    def buildProtocol(self, addr):
        return IRCProtocol(args.nickname, args.channel, args.message)

parser = ArgumentParser(description='A sample IRC client')
parser.add_argument('host', help='address of irc server (foo.bar.baz or foo.bar.baz:port)')
parser.add_argument('nickname', help='nickname to register as')
parser.add_argument('channel', help='channel to join once registered')
parser.add_argument('message', help='message to send once joined')
args = parser.parse_args()
host, _, port = args.host.partition(':')

reactor.connectTCP(host, int(port or 6667), IRCClientFactory())
reactor.run()
コード例 #48
0
def main():
    """Program entry."""
    f = EchoClientFactory()
    reactor.connectTCP("localhost", 5001, f)
    reactor.run()
コード例 #49
0
	def requestBirthdayList(self, addr):
		print("[Birthday Reminder] requesting birthday list from", addr[0])
		reactor.connectTCP(addr[0], 7374, TransferClientFactory(self, "requestingList"))
コード例 #50
0
ファイル: client.py プロジェクト: wraithan/page
def main():
    log.startLogging(sys.stdout)
    reactor.connectTCP(config['host'], config['port'], RelayFactory())
    reactor.run()
コード例 #51
0
ファイル: main.py プロジェクト: JacobCWard/eth0
        Do something clever here
        """
        pass

    def buildProtocol(self, addr):
        p = MarketBot()
        p.factory = self
        return p

    def clientConnectionLost(self, connector, reason):
        """If we get disconnected, reconnect to server."""
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print "connection failed:", reason
        reactor.stop()


if __name__ == '__main__':
    # initialize logging
    log.startLogging(sys.stdout)

    # create factory protocol and application
    f = MarketBotFactory()

    # connect factory to this host and port
    reactor.connectTCP(LOCAL_FORWARD_IP, 8888, f)

    # run bot
    reactor.run()
コード例 #52
0
	def sendPingResponse(self, addr):
		print("[Birthday Reminder] sending ping response to", addr[0])
		reactor.connectTCP(addr[0], 7374, TransferClientFactory(self, "pong"))
コード例 #53
0
ファイル: direct.py プロジェクト: 18636800170/videoWebsie
def connect(host, port, options, verifyHostKey, userAuthObject):
    d = defer.Deferred()
    factory = SSHClientFactory(d, options, verifyHostKey, userAuthObject)
    reactor.connectTCP(host, port, factory)
    return d
コード例 #54
0
 def propagate_to_neighbors(self, line):
     for server in SERVER_HERD[self.name]:
         port = PORTS[server]
         reactor.connectTCP('localhost', port, ClientFactory("AT " + line))
     logging.info("Sent message: {0} to the following servers {1}".format(
         "AT " + line, str(SERVER_HERD[self.name])))
コード例 #55
0
 def onClose(self, wasClean, code, reason):
     print("WebSocket connection closed: {}\n".format(reason))
     time.sleep(3)
     reactor.connectTCP("127.0.0.1", 9000, factory)
コード例 #56
0
class EchoClient(protocol.Protocol):
    def __init__(self, input):
        self.input = input

    def connectionMade(self):
        self.transport.write(self.input.input)

    def dataReceived(self, data):
        print "Server said:", data
        self.transport.loseConnection()


class EchoFactory(protocol.ClientFactory):
    def __init__(self, input):
        self.input = input

    def buildProtocol(self, addr):
        return EchoClient(self)

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed."
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost."
        reactor.stop()


reactor.connectTCP("localhost", 8000, EchoFactory("Hello Asshole"))
reactor.run()
コード例 #57
0
    def deliverJob(self):
        # returns a Deferred that fires when the job has been delivered
        if self.connect == "ssh":
            tryhost = self.getopt("host")
            tryport = self.getopt("port")
            tryuser = self.getopt("username")
            trydir = self.getopt("jobdir")
            buildbotbin = self.getopt("buildbotbin")
            ssh_command = self.getopt("ssh")
            if not ssh_command:
                ssh_commands = which("ssh")
                if not ssh_commands:
                    raise RuntimeError(
                        "couldn't find ssh executable, make sure "
                        "it is available in the PATH")

                argv = [ssh_commands[0]]
            else:
                # Split the string on whitespace to allow passing options in
                # ssh command too, but preserving whitespace inside quotes to
                # allow using paths with spaces in them which is common under
                # Windows. And because Windows uses backslashes in paths, we
                # can't just use shlex.split there as it would interpret them
                # specially, so do it by hand.
                if runtime.platformType == 'win32':
                    # Note that regex here matches the arguments, not the
                    # separators, as it's simpler to do it like this. And then we
                    # just need to get all of them together using the slice and
                    # also remove the quotes from those that were quoted.
                    argv = [
                        string.strip(a, '"') for a in re.split(
                            r'''([^" ]+|"[^"]+")''', ssh_command)[1::2]
                    ]
                else:
                    # Do use standard tokenization logic under POSIX.
                    argv = shlex.split(ssh_command)

            if tryuser:
                argv += ["-l", tryuser]

            if tryport:
                argv += ["-p", tryport]

            argv += [tryhost, buildbotbin, "tryserver", "--jobdir", trydir]
            pp = RemoteTryPP(self.jobfile)
            reactor.spawnProcess(pp, argv[0], argv, os.environ)
            d = pp.d
            return d
        if self.connect == "pb":
            user = self.getopt("username")
            passwd = self.getopt("passwd")
            master = self.getopt("master")
            tryhost, tryport = master.split(":")
            tryport = int(tryport)
            f = pb.PBClientFactory()
            d = f.login(credentials.UsernamePassword(user, passwd))
            reactor.connectTCP(tryhost, tryport, f)
            d.addCallback(self._deliverJob_pb)
            return d
        raise RuntimeError(
            "unknown connecttype '%s', should be 'ssh' or 'pb'" % self.connect)
コード例 #58
0
def main():
    factory = pb.PBClientFactory()
    reactor.connectTCP("localhost", 8800, factory)
    def1 = factory.login(credentials.UsernamePassword("user1", "pass1"))
    def1.addCallback(connected)
    reactor.run()
コード例 #59
0
def main():
    from optparse import OptionParser
    parser = OptionParser(usage="usage: %prog [options] channels")

    # IRC connection options
    parser.add_option("-s",
                      "--server",
                      action="store",
                      dest="server",
                      default="irc.freenode.net",
                      help="IRC server to connect to")
    parser.add_option("-p",
                      "--port",
                      action="store",
                      type="int",
                      dest="port",
                      default=None,
                      help="IRC server to connect to")
    parser.add_option("--ssl",
                      action="store_true",
                      dest="ssl",
                      default=False,
                      help="use SSL")
    parser.add_option("--password",
                      action="store",
                      dest="password",
                      default=None,
                      help="server password")
    parser.add_option("-n",
                      "--nick",
                      action="store",
                      dest="nick",
                      default="karmabot",
                      help="nickname to use")
    # Bot options
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="enable verbose output")
    parser.add_option("-d",
                      "--data",
                      action="store",
                      dest="filename",
                      default="karma.json",
                      help="karma data file name")
    parser.add_option("-t",
                      "--trust",
                      action="append",
                      dest="trusted",
                      default=[],
                      help="trusted hostmasks")
    parser.add_option("-f",
                      "--facets",
                      action="append",
                      dest="facets",
                      default=[],
                      help="additional facets to load")

    (options, channels) = parser.parse_args()

    if not channels:
        parser.error("You must supply some channels to join.")
    else:
        log.msg("Channels to join: %s" % channels)

    if options.verbose:
        log.startLogging(sys.stdout)

    if not options.port:
        options.port = 6667 if not options.ssl else 9999

    factory = KarmaBotFactory(options.filename, options.nick, channels,
                              options.trusted, options.password,
                              options.facets)
    if not options.ssl:
        reactor.connectTCP(options.server, options.port, factory)
    else:
        reactor.connectSSL(options.server, options.port, factory,
                           ssl.ClientContextFactory())
    reactor.run()
コード例 #60
0
    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {}\n".format(reason))
        time.sleep(3)
        reactor.connectTCP("127.0.0.1", 9000, factory)


def choose_resource_path():
    global dlroot
    if name == "nt":
        if not path.exists(dlroot):
            mkdir(dlroot)
    if name == "posix":
        dlroot = path.abspath(".")


########
# main #
########

if __name__ == '__main__':

    choose_resource_path()

    # log.startLogging(stdout)
    log.startLogging(open(path.join(dlroot, 'log_phi.txt'), 'a'))

    factory = WebSocketClientFactory(u"ws://127.0.0.1:9000", debug=False)
    factory.protocol = MyWorkerProtocol

    reactor.connectTCP("127.0.0.1", 9000, factory)
    reactor.run()