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

Python reactor.connectTCP函数代码示例

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

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



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

示例1: connect

    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)
开发者ID:jookies,项目名称:jasmin,代码行数:33,代码来源:proxies.py


示例2: render_POST

 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"
开发者ID:AlexHendy98,项目名称:iris,代码行数:31,代码来源:feedbackengine.py


示例3: main

def main():
    config = hamper.config.load()
    hamper.log.setup_logging()

    reactor.connectTCP(config['server'], config['port'],
            CommanderFactory(config))
    reactor.run()
开发者ID:jalalhobbs,项目名称:hamper,代码行数:7,代码来源:commander.py


示例4: _runTest

    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,))
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:35,代码来源:test_ssl.py


示例5: processAT

	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)
开发者ID:yhenryk,项目名称:CS,代码行数:29,代码来源:Metta.py


示例6: connect_to_pot

    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()
开发者ID:Bifrozt,项目名称:honssh,代码行数:32,代码来源:post_auth_handler.py


示例7: connect

 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)
开发者ID:drednout,项目名称:redis_vs_mysql,代码行数:7,代码来源:redisapi.py


示例8: received_broadcast

 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"]})
开发者ID:0rbytal,项目名称:BAR,代码行数:25,代码来源:bar_daemon.py


示例9: deliverJob

    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)
开发者ID:ahussein,项目名称:buildbot,代码行数:27,代码来源:tryclient.py


示例10: getStatus

 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
开发者ID:ahussein,项目名称:buildbot,代码行数:28,代码来源:tryclient.py


示例11: addRequest

 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
开发者ID:jredrejo,项目名称:controlaula,代码行数:25,代码来源:DownloadFiles.py


示例12: is_already_running

 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)
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:7,代码来源:tcpactivation.py


示例13: main

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()
开发者ID:clawplach,项目名称:BitBlinder,代码行数:7,代码来源:build_all.py


示例14: start

 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
开发者ID:LiMinggang,项目名称:buildbot,代码行数:7,代码来源:test_try_client.py


示例15: sendmail

    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
开发者ID:pepsiman,项目名称:buildbot,代码行数:31,代码来源:mail.py


示例16: _makeDeferredRequest

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
开发者ID:GNOME,项目名称:postr,代码行数:32,代码来源:proxyclient.py


示例17: test_multiprocessing_factory

    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
开发者ID:Grindizer,项目名称:scaletix,代码行数:26,代码来源:test_scaletix.py


示例18: handleStatus_301

 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()
开发者ID:GNOME,项目名称:postr,代码行数:27,代码来源:proxyclient.py


示例19: start

def start(host='localhost', port=61613, username='test', password='test'):
    """Start twisted event loop and the fun should begin...
    """
    StompClientFactory.username = username
    StompClientFactory.password = password
    reactor.connectTCP(host, port, StompClientFactory())
    reactor.run()
开发者ID:NurKaynar,项目名称:hacklab,代码行数:7,代码来源:sender.py


示例20: main

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()
开发者ID:drd,项目名称:karmabot,代码行数:60,代码来源:karmabot.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python reactor.connectUNIX函数代码示例发布时间:2022-05-27
下一篇:
Python reactor.connectSSL函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap