当前位置: 首页>>代码示例>>Python>>正文


Python socket.create_connection函数代码示例

本文整理汇总了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
开发者ID:alanfly,项目名称:goagent,代码行数:26,代码来源:proxy.py

示例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
开发者ID:ulule,项目名称:bokchoy,代码行数:7,代码来源:test_redis.py

示例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')
开发者ID:WHS-TechOps,项目名称:Aviator,代码行数:7,代码来源:run_py_tests.py

示例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
开发者ID:ollmer,项目名称:jane,代码行数:26,代码来源:diagnose.py

示例5: is_connected

def is_connected():
  try:
    socket.create_connection(("www.google.com", 80))
    return True
  except:
    pass
  return False
开发者ID:digitalWestie,项目名称:BitBarista,代码行数:7,代码来源:fserver.py

示例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)
开发者ID:DIXINFOR,项目名称:odoo-7.0,代码行数:33,代码来源:purchase.py

示例7: check

def check(host):
    try:
        socket.create_connection((host, PORT), CONNECT_TIMEOUT)
    except Exception:
        return DOWN
    else:
        return OK
开发者ID:HackerDom,项目名称:ructfe-2014,代码行数:7,代码来源:s7.checker.py

示例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
开发者ID:dghabc,项目名称:goagent,代码行数:35,代码来源:proxy.py

示例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
开发者ID:onlymycode,项目名称:MyTr,代码行数:29,代码来源:proxy.py

示例10: wait_for_kafka

def wait_for_kafka():
    while True:
        try:
            socket.create_connection(("kafka", 9092)).close()
            break
        except ConnectionRefusedError:
            pass
开发者ID:talevy,项目名称:elastic-stack-tests,代码行数:7,代码来源:test.py

示例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()
开发者ID:vaibhavsingh1993,项目名称:CS5700,代码行数:35,代码来源:Client.py

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

示例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
开发者ID:Kayle009,项目名称:sentry,代码行数:7,代码来源:skips.py

示例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()
开发者ID:xtycoon,项目名称:kafka-python,代码行数:35,代码来源:test_conn.py

示例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()
开发者ID:humw,项目名称:ToolBox,代码行数:7,代码来源:lib.py


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