Пример #1
0
 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
0
def redis_is_available():
    try:
        socket.create_connection(('127.0.0.1', 6379), 1.0)
    except socket.error:
        return False
    else:
        return True
Пример #3
0
 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
0
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
0
def is_connected():
  try:
    socket.create_connection(("www.google.com", 80))
    return True
  except:
    pass
  return False
Пример #6
0
    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
0
def check(host):
    try:
        socket.create_connection((host, PORT), CONNECT_TIMEOUT)
    except Exception:
        return DOWN
    else:
        return OK
Пример #8
0
 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
0
 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
0
def wait_for_kafka():
    while True:
        try:
            socket.create_connection(("kafka", 9092)).close()
            break
        except ConnectionRefusedError:
            pass
Пример #11
0
    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
0
    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
0
def cassandra_is_available():
    try:
        socket.create_connection(('127.0.0.1', 9042), 1.0)
    except socket.error:
        return False
    else:
        return True
Пример #14
0
    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
0
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()
Пример #16
0
 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)
Пример #17
0
 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
 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)
Пример #19
0
 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
Пример #20
0
  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)
Пример #21
0
def test_connection(address):
    try:
        socket.create_connection(address)
    except socket.error:
        return False
    else:
        return True
Пример #22
0
 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.connection.sendall('%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])
             if 'Host' in self.headers:
                 del self.headers['Host']
             if common.PROXY_USERNAME and 'Proxy-Authorization' not in self.headers:
                 self.headers['Proxy-Authorization'] = 'Basic %s' + base64.b64encode('%s:%s'%(common.PROXY_USERNAME, common.PROXY_PASSWROD))
             data = '%s %s:%s %s\r\n%s\r\b' % (self.command, ip, port, self.protocol_version, self.headers)
             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
Пример #23
0
    def _serve_synch_app(self, app_id, path, addr):
        conns = (socket.create_connection(addr), socket.create_connection(addr))

        stop_reading = threading.Event()

        for conn, name in zip(conns, ('stdout', 'stderr')):
            args = (path + '/_' + name, conn, stop_reading)
            th = threading.Thread(target = tail_follow, name = name, args = args)
            th.daemon = True
            th.start()

        msg = self.wait_synch_app_queue(app_id) # {'status': status, 'exit_code': exit_code}
        self.remove_synch_app_queue(app_id)

        # not an elegant solution but we need to keep the reader threads alive for just a bit longer
        time.sleep(1)

        stop_reading.set()

        for conn in conns:
            try:
                conn.shutdown(socket.SHUT_RDWR)
            except:
                pass
            conn.close()

        return {'status': AppManager.status_name(msg['status']), 'exit_code': msg['exit_code']}
Пример #24
0
 def do_CONNECT_Direct(self):
     try:
         logging.debug('SimpleProxyHandler.do_CONNECT_Directt %s' % self.path)
         host, _, port = self.path.rpartition(':')
         if not common.PROXY_ENABLE:
             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))
             ip = common.HOSTS_MAP.get(host, host)
             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' % proxy_auth_header(common.PROXY_USERNAME, common.PROXY_PASSWROD)
             data += '\r\n'
             sock.sendall(data)
         socket_forward(self.connection, sock)
     except:
         logging.exception('GaeProxyHandler.do_CONNECT_Direct Error')
     finally:
         try:
             sock.close()
         except:
             pass
Пример #25
0
    def do_pre_handshake(self):
        """Open a socket to the server; setup HTTP tunneling if a proxy was configured."""

        if self._tunnel_host:
            # Proxy configured; setup HTTP tunneling
            try:
                self._sock = socket.create_connection((self._tunnel_host, self._tunnel_port), self.NETWORK_TIMEOUT)
            except socket.timeout as e:
                raise ProxyError(self.ERR_PROXY_OFFLINE.format(e[0]))
            except socket.error as e:
                raise ProxyError(self.ERR_PROXY_OFFLINE.format(e[1]))

            # Send a CONNECT request with the host we want to tunnel to
            if self._tunnel_basic_auth_token is None:
                self._sock.send(self.HTTP_CONNECT_REQ.format(self._host, self._port))
            else:
                self._sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format(self._host, self._port,
                                                                              self._tunnel_basic_auth_token))
            http_response = parse_http_response(self._sock)

            # Check if the proxy was able to connect to the host
            if http_response.status != 200:
                raise ProxyError(self.ERR_CONNECT_REJECTED)
        else:
            # No proxy; connect directly to the server
            self._sock = socket.create_connection((self._ip, self._port), self.NETWORK_TIMEOUT)
Пример #26
0
    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:
                sock = socket.create_connection((host, port))
                self.headers['connection'] = 'close'
                data = '%s %s %s\r\n'  % (self.command, urlparse.urlunparse(('', '', path, params, query, '')), self.request_version)
                data += ''.join('%s: %s\r\n' % (k, self.headers[k]) for k in self.headers if not k.startswith('proxy-'))
                data += '\r\n'
            else:
                sock = socket.create_connection((common.PROXY_HOST, common.PROXY_PORT))
                host = common.HOSTS_MAP.get(host, host)
                url = urlparse.urlunparse((scheme, host + ('' if port == 80 else ':%d' % port), path, params, query, ''))
                data ='%s %s %s\r\n'  % (self.command, url, self.request_version)
                data += ''.join('%s: %s\r\n' % (k, self.headers[k]) for k in self.headers if k != 'host')
                data += 'Host: %s\r\n' % netloc
                if common.PROXY_USERNAME and not common.PROXY_NTLM:
                    data += '%s\r\n' % proxy_auth_header(common.PROXY_USERNAME, common.PROXY_PASSWROD)
                data += 'Proxy-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)
            sock.sendall(data)
            socket_forward(self.connection, sock)
        except Exception, ex:
            logging.exception('GaeProxyHandler.do_GET Error, %s', ex)
Пример #27
0
 def _FindOpenPort(self):
   for port in range(9500, 10000):
     try:
       socket.create_connection(('127.0.0.1', port), 0.2).close()
     except socket.error:
       return port
   raise RuntimeError('Cannot find open port to launch ChromeDriver')
Пример #28
0
    def connect(self):
        import sys
        if sys.version_info >= (2,7,0):
            sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
        else:
            sock = socket.create_connection((self.host, self.port), self.timeout)

        # Note these next fixes require python at least from Oct 2009 so 2.6.3
        if sys.version_info >= (2,6,3):
            if self._tunnel_host:
                self.sock = sock
                self._tunnel()

        # Force use of TLSv1 with PROTOCOL_TLSv1
        # Default is PROTOCOL_SSLv23 which allows either 2 or 3
        # Another option is PROTOCOL_SSLv3
        # We want TLS1 to avoid POODLE vulnerability. In addition, some client/server combinations fail the handshake
        # if you start with SSL23 and the server wants TLS1. See geni-tools issue #745
        if self.ssl_version is None:
            #print "Requested a None ssl version"
            self.ssl_version = ssl.PROTOCOL_TLSv1
        #print "Wrapping socket to use SSL version %s" % ssl._PROTOCOL_NAMES[self.ssl_version]

        if sys.version_info >= (2,7,0):
            #if self.ciphers is None:
            #    print "Using cipherlist: 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'"
            #else:
            #    print "Using cipherlist: '%s'" % self.ciphers
            self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=self.ssl_version, ciphers=self.ciphers)
        else:
            # Python 2.6 doesn't let you specify the ciphers to use
            self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=self.ssl_version)
Пример #29
0
def run(clients, servers, startup=10):
	port = 10000
	server_procs = []
	for server in servers:
		print "starting", server
		proc = subprocess.Popen([sys.executable, server, str(port)], stdout=subprocess.PIPE)
		_PROCS.append(proc)
		server_procs.append(proc)
		proc.port = port
		proc.server_name = server
		start = time.time()
		while time.time() - start < startup:
			try:
				socket.create_connection( ('localhost', port))
				break
			except socket.error:
				pass
		else:  # didn't break
			raise EnvironmentError(
				"server {0} on port {1} didn't come ready within {2}s".format(
					server, port, startup))
		port += 1

	for serv in server_procs:
		print "SERVER", serv.server_name
		for client in clients:
			print "    CLIENT", client.__name__, client(serv.port)

		serv.kill()
Пример #30
0
    def connect(self):
        """
        Connect to the server specified when the object was created. This is a
        no-op if we're already connected.

        :returns: Nothing.
        """
        if self._sock is None:
            if not self.proxy_host:
                host = self.host
                port = self.port
            else:
                host = self.proxy_host
                port = self.proxy_port

            if self.ip:
                sock = socket.create_connection((self.ip, port), 5)
            else:
                sock = socket.create_connection((host, port), 5)

            if self.secure:
                assert not self.proxy_host, "Using a proxy with HTTPS not yet supported."
                sock, proto = wrap_socket(sock, host, self.ssl_context)
            else:
                proto = H2C_PROTOCOL

            log.debug("Selected NPN protocol: %s", proto)
            assert proto in H2_NPN_PROTOCOLS or proto == H2C_PROTOCOL

            self._sock = BufferedSocket(sock, self.network_buffer_size)

            self._send_preamble()

        return