本文整理汇总了Python中twisted.internet.reactor.connectTCP函数的典型用法代码示例。如果您正苦于以下问题:Python connectTCP函数的具体用法?Python connectTCP怎么用?Python connectTCP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connectTCP函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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"
示例3: main
def main():
config = hamper.config.load()
hamper.log.setup_logging()
reactor.connectTCP(config['server'], config['port'],
CommanderFactory(config))
reactor.run()
示例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,))
示例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)
示例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()
示例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)
示例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"]})
示例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)
示例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
示例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
示例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)
示例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()
示例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
示例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