本文整理汇总了Python中socket.create_connection函数的典型用法代码示例。如果您正苦于以下问题:Python create_connection函数的具体用法?Python create_connection怎么用?Python create_connection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create_connection函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_CONNECT_Direct
def do_CONNECT_Direct(self):
try:
logging.debug('GaeProxyHandler.do_CONNECT_Directt %s' % self.path)
host, _, port = self.path.rpartition(':')
if not common.PROXY_ENABLE:
soc = socket.create_connection((host, int(port)))
self.log_request(200)
self.wfile.write('%s 200 Tunnel established\r\n\r\n' % self.protocol_version)
else:
soc = socket.create_connection((common.PROXY_HOST, common.PROXY_PORT))
if host.endswith(common.GOOGLE_SITES):
ip = random.choice(common.GOOGLE_HOSTS[0])
else:
ip = random.choice(common.HOSTS.get(host, host)[0])
data = '%s %s:%s %s\r\n\r\n' % (self.command, ip, port, self.protocol_version)
if common.PROXY_USERNAME:
data += 'Proxy-authorization: Basic %s\r\n' % base64.b64encode('%s:%s'%(urllib.unquote(common.PROXY_USERNAME), urllib.unquote(common.PROXY_PASSWROD))).strip()
soc.sendall(data)
socket_forward(self.connection, soc, maxping=8)
except:
logging.exception('GaeProxyHandler.do_CONNECT_Direct Error')
finally:
try:
soc.close()
except:
pass
示例2: redis_is_available
def redis_is_available():
try:
socket.create_connection(('127.0.0.1', 6379), 1.0)
except socket.error:
return False
else:
return True
示例3: FindFreePort
def FindFreePort(self):
for port in range(10000, 10100):
try:
socket.create_connection(('127.0.0.1', port), 0.2).close()
except socket.error:
return port
raise RuntimeError('Cannot find open port')
示例4: check_network_connection
def check_network_connection(server="www.google.com"):
"""
Checks if jasper can connect a network server.
Arguments:
server -- (optional) the server to connect with (Default:
"www.google.com")
Returns:
True or False
"""
logger = logging.getLogger(__name__)
logger.debug("Checking network connection to server '%s'...", server)
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(server)
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection((host, 80), 2)
except Exception:
logger.debug("Network connection not working")
return False
else:
logger.debug("Network connection working")
return True
示例5: is_connected
def is_connected():
try:
socket.create_connection(("www.google.com", 80))
return True
except:
pass
return False
示例6: envoieCommande
def envoieCommande(self,cr,uid,ids,context):
idPo=self.pool.get('purchase.order.line').search(cr,uid,[('order_id','=',ids[0]),])
requete=self.requeteCode(cr,uid,idPo,ids[0])
try:
idsearch=self.pool.get('ingram_config').search(cr,uid,[('xml_active','=','True'),])
config=self.pool.get('ingram_config').read(cr,uid,idsearch,['xml_address'])#
ip=str(config[0]['xml_address'])
if ip :
ip=ip.split('/')
chm=""
for i in range(len(ip)):
if i>0:
chm+="/"+ip[i]
conn = httplib.HTTPSConnection(ip[0],443)#environment prod
if sys.version >= '2.7':
sock = socket.create_connection((conn.host, conn.port), conn.timeout, conn.source_address)
else:
sock = socket.create_connection((conn.host, conn.port), conn.timeout)
conn.sock = ssl.wrap_socket(sock, conn.key_file, conn.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
conn.request("POST",chm,requete )
except:
raise osv.except_osv(_('Warning!'),_('Connection failed'))
response = conn.getresponse()
if response.status == 200:
data = response.read()
_logger.info(data)
conn.close()
return self.traitement(cr,uid,ids,data)
else:
raise osv.except_osv(_('Information!'),_('Connection failed'))
return self.traitement(cr,uid,ids,data)
示例7: check
def check(host):
try:
socket.create_connection((host, PORT), CONNECT_TIMEOUT)
except Exception:
return DOWN
else:
return OK
示例8: do_CONNECT_Direct
def do_CONNECT_Direct(self):
try:
logging.debug('LocalProxyHandler.do_CONNECT_Directt %s' % self.path)
host, _, port = self.path.rpartition(':')
idlecall = None
if not common.PROXY_ENABLE:
if host.endswith(common.GOOGLE_SITES):
conn = MultiplexConnection(common.GOOGLE_HOSTS, int(port))
sock = conn.socket
idlecall=conn.close
else:
sock = socket.create_connection((host, int(port)))
self.log_request(200)
self.wfile.write('%s 200 Tunnel established\r\n\r\n' % self.protocol_version)
else:
sock = socket.create_connection((common.PROXY_HOST, common.PROXY_PORT))
if host.endswith(common.GOOGLE_SITES):
ip = random.choice(common.GOOGLE_HOSTS)
else:
ip = random.choice(common.HOSTS.get(host, host)[0])
data = '%s %s:%s %s\r\n' % (self.command, ip, port, self.protocol_version)
data += ''.join('%s: %s\r\n' % (k, self.headers[k]) for k in self.headers if k != 'host')
if common.PROXY_USERNAME and not common.PROXY_NTLM:
data += '%s\r\n' % common.proxy_basic_auth_header()
data += '\r\n'
sock.sendall(data)
socket_forward(self.connection, sock, idlecall=idlecall)
except:
logging.exception('LocalProxyHandler.do_CONNECT_Direct Error')
finally:
try:
sock.close()
del sock
except:
pass
示例9: do_CONNECT_Direct
def do_CONNECT_Direct(self):
try:
logging.debug('GaeProxyHandler.do_CONNECT_Directt %s' % self.path)
host, _, port = self.path.rpartition(':')
if not common.PROXY_ENABLE:
soc = socket.create_connection((host, int(port)))
self.log_request(200)
self.wfile.write('%s 200 Connection established\r\nProxy-agent: %s\r\n\r\n' % (self.protocol_version, self.version_string()))
else:
soc = socket.create_connection((common.PROXY_HOST, common.PROXY_PORT))
if host.endswith(common.GOOGLE_SITES):
ip = random.choice(common.GOOGLE_HTTPS[0])
else:
ip = random.choice(common.HOSTS.get(host, host)[0])
data = '%s %s:%s %s\r\n\r\n' % (self.command, ip, port, self.protocol_version)
soc.send(data)
socket_forward(self.connection, soc, maxping=8)
except:
logging.exception('GaeProxyHandler.do_CONNECT_Direct Error')
self.send_error(502, 'GaeProxyHandler.do_CONNECT_Direct Error')
finally:
try:
self.connection.close()
except:
pass
try:
soc.close()
except:
pass
示例10: wait_for_kafka
def wait_for_kafka():
while True:
try:
socket.create_connection(("kafka", 9092)).close()
break
except ConnectionRefusedError:
pass
示例11: run
def run(self):
"""
Use breadth first search to crawl fakebook
"""
page = ''
while self.urls and len(self.flag) < 5:
# if there are unvisited urls or less than 5 flags, continue the loop
link = self.urls.pop(0)
# print '[DEBUG]Open link:%s' % link
try:
page = self.open_url(link)
# print '[DEBUG]Page:\n%s' % page
self.find_url(page)
self.find_secret_flag(page)
except ClientError:
self.visited.append(link) # abandon the URL
except RedirectError:
self.urls.insert(0, self.get_new_url(page))
except ServerError:
self.sock = socket.create_connection((self.host, 80))
self.visited.pop()
self.urls.insert(0, link)
except UnKnowError:
self.sock = socket.create_connection((self.host, 80))
self.visited.pop()
self.urls.insert(0, link)
# print '[DEBUG]Visited:%d' % len(self.visited)
# print self.visited
# print '[DEBUG]URLS:%d' % len(self.urls)
# print self.urls
# print '[DEBUG]secret_flag:'
# for flag in self.flag:
# print flag
self.sock.close()
示例12: run
def run(self):
while 1:
with self.RaceLock:
self.RaceLock.wait()
try:
data = self._pre_otp(self.obj)
#sock = socket.create_connection((TARGET_HOST, 80))
if 'Commit transaction.' in data:
post_data = 'step=step3&' + ('a' * 1896)
step3 = "\r\n".join(
('POST /transaction.php HTTP/1.1'
, 'Host: {0}'.format(TARGET_HOST)
, 'Cookie: {0}'.format(self.obj.gen_auth_cookie())
, 'User-Agent: Python-urllib/2.7'
, 'Content-Type: application/x-www-form-urlencoded'
, 'Content-Length: {0}'.format(len(post_data))
, 'Connection: Close'
, ''
, post_data
)
)
a = [HTTPRace(step3, socket.create_connection((TARGET_HOST, 80))) for race_obj in
xrange(CONCURRENT_RACE)]
asyncore.loop(0.15, count=20)
map(lambda x: x.send_end(), a)
asyncore.loop(0.15, count=30)
# 2) SmartCard otp
elif 'One-time password:' in data:
post_data = 'step=step4&' + ('a' * 4096 * 2)
step4 = "\r\n".join(('POST /transaction.php HTTP/1.1'
, 'Host: {0}'.format(TARGET_HOST)
, 'Cookie: {0}'.format(self.obj.gen_auth_cookie())
, 'User-Agent: Python-urllib/2.7'
, 'Content-Type: application/x-www-form-urlencoded'
, 'Content-Length: {0}'.format(len(post_data))
, 'Connection: Close'
, ''
, post_data
))
a = [HTTPRace(step4, socket.create_connection((TARGET_HOST, 80))) for race_obj in
xrange(CONCURRENT_RACE)]
asyncore.loop(0.15, count=20)
map(lambda x: x.send_end(), a)
asyncore.loop(0.15, count=30)
# 3) Brute otp
elif 'One-time password (#' in data:
tmp_ticket = RE_TICKET.search(data)
if not tmp_ticket:
return False
tmp_ticket = tmp_ticket.group(1)
# Implement dupe for OTP list
except Exception as e:
raise
finally:
with self.RaceLock:
self.RaceLock.notify()
示例13: cassandra_is_available
def cassandra_is_available():
try:
socket.create_connection(('127.0.0.1', 9042), 1.0)
except socket.error:
return False
else:
return True
示例14: setUp
def setUp(self):
self.config = {
'host': 'localhost',
'port': 9090,
'request_id': 0,
'payload': 'test data',
'payload2': 'another packet'
}
# Mocking socket.create_connection will cause _sock to always be a
# MagicMock()
patcher = mock.patch('socket.create_connection', spec=True)
self.MockCreateConn = patcher.start()
self.addCleanup(patcher.stop)
# Also mock socket.sendall() to appear successful
socket.create_connection().sendall.return_value = None
# And mock socket.recv() to return two payloads, then '', then raise
# Note that this currently ignores the num_bytes parameter to sock.recv()
payload_size = len(self.config['payload'])
payload2_size = len(self.config['payload2'])
socket.create_connection().recv.side_effect = [
struct.pack('>i', payload_size),
struct.pack('>%ds' % payload_size, self.config['payload']),
struct.pack('>i', payload2_size),
struct.pack('>%ds' % payload2_size, self.config['payload2']),
''
]
# Create a connection object
self.conn = KafkaConnection(self.config['host'], self.config['port'])
# Reset any mock counts caused by __init__
socket.create_connection.reset_mock()
示例15: tcp_probe
def tcp_probe(ip_addr, port):
try:
socket.create_connection((ip_addr, port), timeout=10)
return True
except socket.error as e:
return False
s.close()