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

Python socket.create_connection函数代码示例

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

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



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


示例16: do_METHOD_Direct

 def do_METHOD_Direct(self):
     scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.path, 'http')
     try:
         host, _, port = netloc.rpartition(':')
         port = int(port)
     except ValueError:
         host = netloc
         port = 80
     try:
         self.log_request()
         if not common.PROXY_ENABLE:
             soc = socket.create_connection((host, port))
             data = '%s %s %s\r\n'  % (self.command, urlparse.urlunparse(('', '', path, params, query, '')), self.request_version)
         else:
             soc = socket.create_connection((common.PROXY_HOST, common.PROXY_PORT))
             if host.endswith(common.GOOGLE_SITES):
                 host = random.choice(common.GOOGLE_HTTPS[0])
             else:
                 host = common.HOSTS.get(host, host)
             data = '%s %s:%d %s\r\n'  % (self.command, host, port, self.request_version)
             data += 'Host: %s\r\n' % host
             data += 'Proxy-Connection: close\r\n'
         data += ''.join('%s: %s\r\n' % (k, self.headers[k]) for k in self.headers if not k.lower().startswith('proxy-'))
         data += 'Connection: close\r\n'
         data += '\r\n'
         content_length = int(self.headers.get('content-length', 0))
         if content_length > 0:
             data += self.rfile.read(content_length)
         soc.send(data)
         socket_forward(self.connection, soc, maxping=10)
     except Exception, ex:
         logging.exception('SimpleProxyHandler.do_GET Error, %s', ex)
         self.send_error(502, 'SimpleProxyHandler.do_GET Error (%s)' % ex)
开发者ID:onlymycode,项目名称:MyTr,代码行数:33,代码来源:proxy.py


示例17: actualisationPrix

 def actualisationPrix(self,config,product):
     if not self:
         sale_order_line=self.env['sale.order.line']
         self=sale_order_line.browse(1)
     requete=self.requeteCode(config,product)
     ip=str(config.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)
         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[0]) 
         response = conn.getresponse()
         data = response.read()  
         _logger.info(data) 
         conn.close()
         return  self.traitement(data)[0]
     else :
         return False
开发者ID:LiberTang0,项目名称:odoo,代码行数:26,代码来源:sale.py


示例18: _connect

 def _connect(self):
     if not self._socket:
         if self._timeout:
             self._socket = socket.create_connection(self._address,
                                                     self._timeout)
         else:
             self._socket = socket.create_connection(self._address)
开发者ID:linearregression,项目名称:riak-python-client,代码行数:7,代码来源:connection.py


示例19: checkPrice

 def checkPrice(self,cr,uid,ids,codeSku,product):
     requete=self.requeteCode(cr,uid,codeSku)
     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)
         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 ) 
         response = conn.getresponse()
         data = response.read()  
         _logger.info(data) 
         conn.close()
         return  self.traitement(cr,uid,ids,data,product)# 
     else :
         return False
开发者ID:DIXINFOR,项目名称:odoo-7.0,代码行数:25,代码来源:purchase.py


示例20: _StartMsrServerIfNeeded

  def _StartMsrServerIfNeeded(self):
    if self._msr_server_handle:
      return

    _InstallWinRing0()

    pipe_name = r"\\.\pipe\msr_server_pipe_{}".format(os.getpid())
    # Try to open a named pipe to receive a msr port number from server process.
    pipe = win32pipe.CreateNamedPipe(
        pipe_name,
        win32pipe.PIPE_ACCESS_INBOUND,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 32, 32, 300, None)
    parameters = (
        os.path.join(os.path.dirname(__file__), 'msr_server_win.py'),
        pipe_name,
    )
    self._msr_server_handle = self.LaunchApplication(
        sys.executable, parameters, elevate_privilege=True)
    if pipe != win32file.INVALID_HANDLE_VALUE:
      if win32pipe.ConnectNamedPipe(pipe, None) == 0:
        self._msr_server_port = int(win32file.ReadFile(pipe, 32)[1])
      win32api.CloseHandle(pipe)
    # Wait for server to start.
    try:
      socket.create_connection(('127.0.0.1', self._msr_server_port), 5).close()
    except socket.error:
      self.CloseMsrServer()
    atexit_with_log.Register(TerminateProcess, self._msr_server_handle)
开发者ID:abhimnc,项目名称:catapult,代码行数:29,代码来源:win_platform_backend.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python socket.error函数代码示例发布时间:2022-05-27
下一篇:
Python socket.connect函数代码示例发布时间: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