Example #1
0
 def WebSocketConnection(self):
     if not self.verify_cert:
         self.ws = None
         self.ws = create_connection(self.url, enable_multithread=True,
                                     sslopt={"cert_reqs": ssl.CERT_NONE})
     else:
         self.ws = None
         if self.identity is not None:
             if self.identity.root_ca_cert:
                 if not (os.path.exists(self.identity.root_ca_cert)):
                     log.error("Error : Wrong CA certificate path.")
                     raise ValueError("Error : Wrong CA certificate path.")
             else:
                 log.error("Error : CA certificate path is missing")
                 raise ValueError("Error : CA certificate path is missing")
             if os.path.isfile(self.identity.root_ca_cert):
                 try:
                     self.ws = create_connection(self.url, enable_multithread=True,
                                                 sslopt={"cert_reqs": ssl.CERT_REQUIRED,
                                                         "ca_certs": self.identity.root_ca_cert})
                 except ssl.SSLError:
                     log.exception("SSL Error during Websocket connection.")
                     raise Exception("SSL Error during Websocket connection.")
         else:
             log.error("Identity object is missing")
             raise ValueError("Identity object is missing")
         if self.ws is None:
             raise (IOError("Couldn't verify host certificate"))
Example #2
0
    def __init__(self, url, timeout=10):
        if not url.endswith('/'):
            url+='/'
        # POST or GET <url>/kernel
        # if there is a terms of service agreement, you need to
        # indicate acceptance in the data parameter below (see the API docs)

        reply = requests.post(
            url+'kernel',
            data={'accepted_tos':'true'},
            headers={'Accept': 'application/json'},
        )

        # Subsequent connections (including websocket) must preserve
        # the cookies for the backend to route to the right server
        cookie = ''
        for key, value in reply.cookies.items():
            cookie += '{0}={1}; '.format(key, value)

        # RESPONSE: {"id": "ce20fada-f757-45e5-92fa-05e952dd9c87", "ws_url": "ws://localhost:8888/"}
        # construct the iopub and shell websocket channel urls from that
        response = reply.json()

        self.kernel_url = response['ws_url']+'kernel/'+response['id']+'/'
        websocket.setdefaulttimeout(timeout)
        print self.kernel_url
        self._shell = websocket.create_connection(self.kernel_url+'shell', cookie=cookie)
        self._iopub = websocket.create_connection(self.kernel_url+'iopub', cookie=cookie)

        # initialize our list of messages
        self.shell_messages = []
        self.iopub_messages = []
Example #3
0
    def run(self):        
        while self.terminate == False:
            try:
                if hasattr(self, 'ws_rs'):
                    del self.ws_rx
                if hasattr(self, 'ws_tx'):
                    del self.ws_tx

                self.ws_rx = websocket.create_connection('%s/receive' % self.host)
                self.ws_tx = websocket.create_connection('%s/submit' % self.host)
                self.send_keepalives = True

                print 'connected!'
                while True and not self.terminate:
                    msg = json.loads(self.ws_rx.recv())
                    if msg.get('handle') == 'FIRE':
                        if time.time() - int(msg.get('timestamp','0')) < MESSAGE_DISCARD_THRESHOLD:
                            self.squirtgun.pulse(float(msg.get('text', '0.5')))
            except websocket.WebSocketConnectionClosedException, e:
                print 'connection closed'
                self.send_keepalives = False
            except socket.error, e:
                if e.errno == 61:
                    print 'connection refused'
                else:
                    print 'socket error number %d' % e.errno
                self.send_keepalives = False
Example #4
0
def ServerWait():
    ws = create_connection(SOCKET_CONNECTION_URL)

    # When program starts, open a connection and send a websocket packet to server with following command
    # IMPORTANT: whisper_id is a pre-existing number associated with already-created whispers on the server,
    # so send me something that i have sent you already...
    message = {"pi_incoming_username": PI_USERNAME}
    message_str = json.dumps(message)
    print "Sending " + message_str
    ws.send(message_str)

    while True:
        try:
            result =  ws.recv()
            print "Received '%s'" % result
            json_object = json.loads(result)
            whisper_id = json_object['whisper_id']
            PostRequest(whisper_id)
        except KeyboardInterrupt:
            exit()
            break
        except Exception, e:
            print e.message
            print "Reconnecting in 30 seconds.."
            time.sleep(10)
            ws = create_connection(SOCKET_CONNECTION_URL)
            ws.send(message_str)
            print("[SOCKET] " + PI_USERNAME + " connection restablished...")
Example #5
0
def main():
    ws = create_connection("ws://88.198.19.60:9001/")
    tw_client = get_twitter_client()
    current_state = 0
    counter = 0
    last_tweet_time = 0

    while True:
        try:
            data = get_socket_data(ws, 'Parrulaituri', 'Analog Sensor Data', 'Soil moisture')
            # data = get_socket_data(ws, 'Light Sensor Data', 'Illuminance')
            # data = get_socket_data(ws, 'Parrulaituri', 'Barometer Sensor Data', 'Temperature')
            value = data.get(u'value')
            if value is None:
                continue
            tweet, current_state = get_tweet(value, current_state, last_tweet_time)
            logger.debug(tweet, current_state, value)
            if tweet is not None:
                tw_client.statuses.update(status=tweet)
                last_tweet_time = time.time()
        except Exception as e:
            logger.exception(e)
            ws = create_connection("ws://88.198.19.60:9001/")
            tw_client = get_twitter_client()
        counter += 1
        if counter > 300:
            break
Example #6
0
    def init_websocket():
        try:
            GlobalVars.metasmoke_ws = websocket.create_connection(
                GlobalVars.metasmoke_ws_host, origin=GlobalVars.metasmoke_host
            )
            payload = json.dumps(
                {
                    "command": "subscribe",
                    "identifier": '{"channel":"SmokeDetectorChannel",' '"key":"' + GlobalVars.metasmoke_key + '"}',
                }
            )
            GlobalVars.metasmoke_ws.send(payload)

            while True:
                a = GlobalVars.metasmoke_ws.recv()
                try:
                    data = json.loads(a)
                    Metasmoke.handle_websocket_data(data)
                except Exception, e:
                    GlobalVars.metasmoke_ws = websocket.create_connection(
                        GlobalVars.metasmoke_ws_host, origin=GlobalVars.metasmoke_host
                    )
                    payload = json.dumps({"command": "subscribe", "identifier": '{"channel":"SmokeDetectorChannel"}'})
                    GlobalVars.metasmoke_ws.send(payload)
                    print e
                    try:
                        exc_info = sys.exc_info()
                        traceback.print_exception(*exc_info)
                    except:
                        print "meh"
        except:
            print "Couldn't bind to MS websocket"
    def test_reuseSessionId(self):
        on_close = lambda(ws): self.assertFalse(True)

        ws_url = 'ws:' + base_url.split(':',1)[1] + \
                 '/000/' + str(uuid.uuid4()) + '/websocket'
        ws1 = websocket.create_connection(ws_url, on_close=on_close)
        self.assertEqual(ws1.recv(), u'o')

        ws2 = websocket.create_connection(ws_url, on_close=on_close)
        self.assertEqual(ws2.recv(), u'o')

        ws1.send(u'"a"')
        self.assertEqual(ws1.recv(), u'a["a"]')

        ws2.send(u'"b"')
        self.assertEqual(ws2.recv(), u'a["b"]')

        ws1.close()
        ws2.close()

        # It is correct to reuse the same `session_id` after closing a
        # previous connection.
        ws1 = websocket.create_connection(ws_url)
        self.assertEqual(ws1.recv(), u'o')
        ws1.send(u'"a"')
        self.assertEqual(ws1.recv(), u'a["a"]')
        ws1.close()
 def test_forbidden_channel(self):
     websocket_url = self.websocket_base_url + u'?subscribe-broadcast&publish-broadcast'
     try:
         create_connection(websocket_url, header=['Deny-Channels: YES'])
         self.fail('Did not reject channels')
     except WebSocketException:
         self.assertTrue(True)
Example #9
0
    def test_client(self):
        # websocket.enableTrace(True)
        ws = websocket.create_connection("ws://127.0.0.1:8888/talk/chat/room_hipo/?token=TOKEN_1234")
        # TODO: wait until authorization
        time.sleep(2)
        d = json.dumps(dict(
            body="hello world",
            type="message"

        ))
        ws.send(d)

        d = json.dumps(dict(
            body="hello 2222",
            type="message"

        ))
        ws.send(d)

        result = ws.recv()
        print "result --- ", result
        ws.close()

        resp = requests.get(
            'http://127.0.0.1:8888/talk/history/room_hipo,room_foo?token=TOKEN_1234'
        )
        data = json.loads(resp.content)
        self.assertEquals(data['results'][0]['messages'][0]["body"], "hello 2222")
        self.assertEquals(len(data['results'][1]["messages"]), 0)

        ws = websocket.create_connection("ws://127.0.0.1:8888/talk/chat/room_hipo/?token=TOKEN_5555")
        time.sleep(5)
        d = json.dumps(dict(
            body="hello world 3333",
            type="message"

        ))
        ws.send(d)

        d = json.dumps(dict(
            body="hello 4444",
            type="message"

        ))
        ws.send(d)

        ws.close()

        resp = requests.get(
            'http://127.0.0.1:8888/talk/old/room_hipo?token=TOKEN_1234'
        )
        data = json.loads(resp.content)

        print "================================"
        print "un......"
        print data['results']['unread_messages'][0]
        print "================================"
        self.assertEquals(data['results']['read_messages'][0]["body"], "hello 2222")
        self.assertEquals(data['results']['unread_messages'][0]["body"], "hello 4444")
def test_asgi_ws_order_0(site, asgi):
    # websocket.connect['order'] should always be 0
    ws1 = create_connection(site.ws_url, timeout=2)
    asgi_connect1 = asgi.receive_ws_connect()
    assert asgi_connect1['order'] == 0
    ws2 = create_connection(site.ws_url, timeout=2)
    asgi_connect2 = asgi.receive_ws_connect()
    assert asgi_connect2['order'] == 0
Example #11
0
 def __init__(self, ph):
     pubport = ":1990"
     hunterport = ":1991"
     preyport = ":1992"
     host = "ws://localhost"
     self.ph = ph
     self.pubsocket = create_connection(host + pubport)
     self.phsocket = create_connection(host + (preyport if ph == 'p' else hunterport))
Example #12
0
def run():
    from websocket import create_connection

    uri = 'ws://%s:%s/:/websockets/notifications' % (
        plexcs.CONFIG.PMS_IP,
        plexcs.CONFIG.PMS_PORT
    )

    # Set authentication token (if one is available)
    if plexcs.CONFIG.PMS_TOKEN:
        uri += '?X-Plex-Token=' + plexcs.CONFIG.PMS_TOKEN

    ws_connected = False
    reconnects = 0

    # Try an open the websocket connection - if it fails after 15 retries fallback to polling
    while not ws_connected and reconnects <= 15:
        try:
            logger.info(u'Plex:CS WebSocket :: Opening websocket, connection attempt %s.' % str(reconnects + 1))
            ws = create_connection(uri)
            reconnects = 0
            ws_connected = True
            logger.info(u'Plex:CS WebSocket :: Ready')
        except IOError as e:
            logger.error(u'Plex:CS WebSocket :: %s.' % e)
            reconnects += 1
            time.sleep(5)

    while ws_connected:
        try:
            process(*receive(ws))

            # successfully received data, reset reconnects counter
            reconnects = 0
        except websocket.WebSocketConnectionClosedException:
            if reconnects <= 15:
                reconnects += 1

                # Sleep 5 between connection attempts
                if reconnects > 1:
                    time.sleep(5)

                logger.warn(u'Plex:CS WebSocket :: Connection has closed, reconnecting...')
                try:
                    ws = create_connection(uri)
                except IOError as e:
                    logger.info(u'Plex:CS WebSocket :: %s.' % e)

            else:
                ws_connected = False
                break

    if not ws_connected:
        logger.error(u'Plex:CS WebSocket :: Connection unavailable, falling back to polling.')
        plexcs.POLLING_FAILOVER = True
        plexcs.initialize_scheduler()

    logger.debug(u'Plex:CS WebSocket :: Leaving thread.')
def test_host_api_garbage_token(client):
    hosts = client.list_host(kind='docker', removed_null=True)
    assert len(hosts) > 0

    # pass garbage token
    stats = hosts[0].stats()
    with pytest.raises(Exception) as excinfo:
        ws.create_connection(stats.url+'?token=abcd')
    assert 'Handshake status 401' in str(excinfo.value)
Example #14
0
def test():
    log_debug('register', 'start testing ')
    get_pkgs_details_cnt = 0
    for i in range(TEST_ROUNDS):
        if SHOW_TIME:
            start_time = datetime.utcnow()
        
        if RANDOM_CAT:
            cat_num = randint(0, len(CAT) - 1)
            cat_name = CAT[cat_num]
            if not CATEGORIES.has_key(cat_name):
                log_err('get_packages_details', 'failed to get the category, invalid category is %s' % str(cat_name))
                return False
            cate = CATEGORIES[cat_name]
        else:
            cate = CATEGORY
        
        message = json.dumps({'operator':'get_counter', 'category':cate})
        ws = create_connection("ws://%s:%d/" % (get_manager(), get_port()))
        ws.send(message)
        ret = ws.recv()
        ws.close()
        result = json.loads(ret)
        if not result or 'get_counter' != result['operator'] or cate != result['category'] or not  result['data']:
            log_err('get_counter', 'failed to get counter')
            return False
        counter = result['data']
        if not counter:
            log_err('get_counter', 'failed to get the total number of %s ' % str(cate))
            return False
        if SHOW_TIME:
            log_debug('get_counter', 'time=%d sec' % (datetime.utcnow() - start_time).seconds)
        log_debug('get_counter', 'counter=%s' % str(counter))
        rank = randint(0, (int(counter)  + PAGE_SIZE  - 1) / PAGE_SIZE - 1)
        log_debug('get_counter', 'rank=%d' % rank)
        
        if SHOW_TIME:
            start_time = datetime.utcnow()
        message = json.dumps({'operator':'get_packages_details', 'category':cate, 'rank':rank})
        ws = create_connection("ws://%s:%d/" % (get_manager(), get_port()))
        ws.send(message)
        ret = ws.recv()
        ws.close()
        result = json.loads(ret)
        if not result or 'get_packages_details' != result['operator'] or cate != result['category'] or rank != result['rank'] or not  result['data']:
            log_err('get_packages_details', 'failed to get packages details')
            return False
        ret = result['data']
        for item in ret:
            if not item['pkg'] or not item['title'] or not item['auth']:
                log_err('get_packages_details', 'failed to get valid details')
                return False
        if SHOW_TIME:
            log_debug('get_packages_details', 'time=%d sec' % (datetime.utcnow() - start_time).seconds)
        get_pkgs_details_cnt += 1
        log_debug('get_packages_details', 'get_pkgs_details_cnt=%d' % get_pkgs_details_cnt)
        log_debug('get_packages_details', 'packages_details=%s' % str(ret))
Example #15
0
 def __init__(self):
     f = urllib2.urlopen("%s/kernel" % (root,), "")
     data = json.loads(f.read())
     f.close()
     self.kernel_id = data["kernel_id"]
     self.ws_url = data["ws_url"]
     self.iopub = websocket.create_connection("%skernel/%s/iopub" % (self.ws_url, self.kernel_id))
     self.shell = websocket.create_connection("%skernel/%s/shell" % (self.ws_url, self.kernel_id))
     self.session_id = str(uuid.uuid4())
Example #16
0
 def connect_targetID(self, targetID):
     try:
         wsurl = 'ws://{}:{}/devtools/page/{}'.format(self.host, self.port, targetID)
         self.close()
         self.ws = websocket.create_connection(wsurl)
         self.ws.settimeout(self.timeout)
     except:
         wsurl = self.tabs[0]['webSocketDebuggerUrl']
         self.ws = websocket.create_connection(wsurl)
         self.ws.settimeout(self.timeout)
def main():
    """docstring for main"""
    publisher = websocket.create_connection("ws://localhost:1990")
    if sys.argv[1] == "H":
        role = "H"
        port = "1991"
        url = "ws://localhost:" + port
        ws = websocket.create_connection(url)
        # prey = websocket.create_connection("ws://localhost:1992")
    else:
        role = 'P'
        port = "1992"
        url = "ws://localhost:" + port
        ws = websocket.create_connection(url)
        # hunter = websocket.create_connection("ws://localhost:1991")

    print "%s, Welcome!" % role
    test = None

    while True:
        times = 1
        if role == "H":
            times = 2
        for i in range(times):
            a = raw_input("command >")
            pack = {}
            if a == "B":
                wall_length = raw_input("wall_lenth >")
                wall_direct = raw_input("wall direction >")
                pack = {"command": "B", "wall": {"length": wall_length,
                                                 "direction": wall_direct}}
            elif a == "D":
                wall_index = raw_input("wall index>")
                pack = {"command": "D", "wallindex": wall_index}
            elif a == "M":
                if role == "P":
                    direction = raw_input("move direction>")
                    pack = {"command": "M", "direction": direction}
                else:
                    pack = {"command": "M"}
            elif a == "P":
                pack = {"command": "P"}
            elif a == "W":
                pack = {"command": "W"}
            else:
                print "unknown command"
                continue
            json_string = json.dumps(pack)
            print "==|| message sent: %s" % json_string
            ws.send(json_string)
            test = 1

            if a == "P" or a == "W":
                result = ws.recv()
                print "==|| Get message: %s" % result
Example #18
0
	def __init__(self):
		domain = raw_input('Enter server address(enter blank for default)')
		print('connecting to server....')
		if domain:
			self.ws = websocket.create_connection(domain)
		else:
			self.ws = websocket.create_connection('ws://py2pyrpc.herokuapp.com/')
		print('waking up server....')
		time.sleep(3)
		print(self.ws.recv())
		thread.start_new_thread(self.pinger,(),)
Example #19
0
    def __init__(self):
        self.__token = self.get_token()
        self.__closeConnectionOnError = False
        self.script_path = customConfig.websocket_url + "/" + self.get_token()
        self.__subscribe_message_id = None
        self.callback_map = customConfig.callback_map
        websocket.enableTrace(True)
        self.__subscribe_unsubscribe_ws = create_connection(self.script_path)
        sub_unsub_count = 0
        #First we have to check if the websocket is connected
        #if it's not connected we will attempt to connect up to 10 times

        if not self.__subscribe_unsubscribe_ws.connected and sub_unsub_count < 10:
            while not self.__subscribe_unsubscribe_ws.connected:
                sub_unsub_count += 1
                self.__subscribe_unsubscribe_ws = create_connection(self.script_path)
        elif sub_unsub_count > 10 and not self.__subscribe_unsubscribe_ws.connected:
            logging.exception("Connection to scriptr via websocket couldn't be established.")

        #same as the previous websocket connection
        pub_count = 0
        self.__publish_ws = create_connection(self.script_path)
        if not self.__publish_ws.connected and pub_count < 10:
            while not self.__publish_ws.connected:
                pub_count += 1
                self.__publish_ws = create_connection(self.script_path)
        elif pub_count > 10 and not self.__publish_ws.connected:
            logging.exception("Connection to scriptr via websocket couldn't be established.")
        # Function executed from threads that listens to the websockets responses
        def __listen(ws, message, **args):
            while ws.connected:
                listen_result = ws.recv()
                message = listen_result
                print(message)
                if (self.__subscribe_message_id and message == "sub_unsub"):
                    for i in range(0, len(self.get_callback_map[self.__subscribe_message_id])):
                        callback_function = self.get_callback_map[self.__subscribe_message_id][i]
                        callback_function(message)
                if (self.get_close_connection_flag()):
                    ws.close()

        # create two threads that handles the websocket connections.
        try:
            process_sub_unsub_thread = threading.Thread(target=__listen,
                                                        args=[self.__subscribe_unsubscribe_ws, "sub_unsub"])
            process_sub_unsub_thread.start()
        except threading.TIMEOUT_MAX as e:
            logging.exception("An error with a thread has occurred!")

        try:
            process_pub_thread = threading.Thread(target=__listen, args=[self.__publish_ws, "publish"])
            process_pub_thread.start()
        except threading.TIMEOUT_MAX as e:
            logging.exception("An error with a thread has occurred!")
    def test_receving_move_message_from_same_channel(self):
        ws2 = create_connection("ws://localhost:8888/ws")
        ws2.send('{"type":"register","args":{"channel_id":"1"}}')

        ws = create_connection("ws://localhost:8888/ws")
        ws.send('{"type":"move","args":{"channel_id":"1","postit_id":2,"x":1,"y":2}}')

        received_message = json.loads(ws2.recv())
        expected_message = {"type":"move","args":{"postit_id":2,"x":1,"y":2}}

        ws2.close()
        ws.close()
        assert received_message == expected_message
Example #21
0
 def execute(self, code):
     r = urllib.request.urlopen(self.req)
     d = json.loads(r.read().decode('utf-8'))
     self.kernel_url = '{}kernel/{}/'.format(d['ws_url'], d['kernel_id'])
     logging.debug(self.kernel_url)
     _shell = websocket.create_connection(self.kernel_url + 'shell')
     _iopub = websocket.create_connection(self.kernel_url + 'iopub')
     _shell.send(self._make_execute_request(code))
     msg_list = self._get_iopub_messages(_iopub)
     #msg_list = self._get_shell_messages(self._shell)
     _shell.close()
     _iopub.close()
     return msg_list
Example #22
0
 def reconnect(self):
     """重连"""
     try:
         if not self.proxyHost:
             self.ws = create_connection(self.url)
         else:
             self.ws = create_connection(self.url, 
                                         http_proxy_host=self.proxyHost, 
                                         http_proxy_port=self.proxyPort)
         return True
     except:
         msg = traceback.format_exc()
         self.onError(u'行情服务器重连失败:%s' %msg)            
         return False
 def test_protocol_support(self):
     protocol = 'unittestprotocol'
     websocket_url = self.websocket_base_url + u'?subscribe-broadcast&publish-broadcast'
     ws = create_connection(websocket_url, subprotocols=[protocol])
     self.assertTrue(ws.connected)
     self.assertIn('sec-websocket-protocol', ws.headers)
     self.assertEqual(protocol, ws.headers['sec-websocket-protocol'])
     ws.close()
     self.assertFalse(ws.connected)
     ws = create_connection(websocket_url)
     self.assertTrue(ws.connected)
     self.assertNotIn('sec-websocket-protocol', ws.headers)
     ws.close()
     self.assertFalse(ws.connected)
Example #24
0
def connect_mtgox():
    try:
        print "Connecting to MtGox websocket..."
        sock = websocket.create_connection(MTGOX_SOCKET, TIMEOUT)
    except socket.timeout:
        print "Connection timed out. Trying backup socket..."
        sock = websocket.create_connection(MTGOX_SOCKET_BACKUP, TIMEOUT)
    except websocket.WebSocketException:
        print "Connection FAILED! Reverting to HTTP API"
        return None
    print "Connected!"
    ticker_cmd = "{'op':'mtgox.subscribe', 'type':'ticker'}"
    sock.send(ticker_cmd)
    sock.recv()
    return sock 
Example #25
0
def send_movement_ws(zone, character, xmod=0, ymod=0):
    import websocket
    global MOVEMENTWEBSOCKET
    if MOVEMENTWEBSOCKET is None:
        connstr = zone.replace("http://", "ws://")
        connstr = ''.join((connstr, "/movement"))
        websocket.enableTrace(True)
        print connstr
        print websocket.create_connection(connstr)
        MOVEMENTWEBSOCKET = create_connection(connstr)
    else:
        print "Using old websocket connection."

    MOVEMENTWEBSOCKET.send(json.dumps({'command': 'mov', 'char':character, 'x':xmod, 'y':ymod}))
    return json.loads(ws.recv())
Example #26
0
 def _connect_to_server(self):  # pragma: no cover
     if not self._is_connected():
         logger.debug('Try connecting to the Websocket server at '
                      + self._ws_url)
         self._ws_connection = create_connection(self._ws_url)
         self._is_running = True
         logger.debug('Connected to the Websocket server')
Example #27
0
    def handshake(self, model_name, model_owner=None):
        """
        Parameters
        ----------
        model_name: string
            name of the model you want to connect to
        model_owner: string
            username of the model owner for shared models. optional

        Returns
        -------
        ws: WebSocket connection
            a connection to the model's WebSocketServer
        """
        ws_uri = "{BASE_URI}/{USERNAME}/models/{MODEL_NAME}/"
        ws_base = self.base_uri.replace("http://", "ws://")
        username = self.username if model_owner is None else model_owner
        ws_uri = ws_uri.format(BASE_URI=ws_base, USERNAME=username,
                               MODEL_NAME=model_name)
        ws_uri = "%s?username=%s&apikey=%s" % (ws_uri, self.username, self.apikey)
        ws = websocket.create_connection(ws_uri)
        auth = {
            "username": self.username,
            "apikey": self.apikey
        }
        ws.send(json.dumps(auth))
        return ws
 def testAfterClose(self):
     from socket import error
     s = ws.create_connection("ws://echo.websocket.org/")
     self.assertNotEqual(s, None)
     s.close()
     self.assertRaises(error, s.send, "Hello")
     self.assertRaises(error, s.recv)
Example #29
0
    def _open_web_socket(self, use_secure=True):
        """
        Opens the web socket connection with the APIC.

        :param use_secure: Boolean indicating whether the web socket
                           should be secure.  Default is True.
        """
        sslopt = {}
        if use_secure:
            sslopt['cert_reqs'] = ssl.CERT_NONE
            self._ws_url = 'wss://%s/socket%s' % (self._apic.ipaddr,
                                                  self._apic.token)
        else:
            self._ws_url = 'ws://%s/socket%s' % (self._apic.ipaddr,
                                                 self._apic.token)

        kwargs = {}
        if self._ws is not None:
            if self._ws.connected:
                self._ws.close()
                self.event_handler_thread.exit()
        try:
            self._ws = create_connection(self._ws_url, sslopt=sslopt, **kwargs)
            if not self._ws.connected:
                logging.error('Unable to open websocket connection')
            self.event_handler_thread = EventHandler(self)
            self.event_handler_thread.daemon = True
            self.event_handler_thread.start()
        except WebSocketException:
            logging.error('Unable to open websocket connection due to WebSocketException')
        except socket.error:
            logging.error('Unable to open websocket connection due to Socket Error')
    def test_close_connection(self):

        class Counter:
            def __init__(self):
                self.value = 0

        counter = Counter()
        old_handle_error = WSGIServer.handle_error

        def handle_error(self, *args, **kwargs):
            # we need a reference to an object for this to work not a simple variable
            counter.value += 1
            return old_handle_error(self, *args, **kwargs)

        WSGIServer.handle_error = handle_error

        statuses = [1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1015, ]
        websocket_url = self.websocket_base_url + u'?subscribe-broadcast&publish-broadcast'
        for status in statuses:
            value_before = counter.value
            ws = create_connection(websocket_url)
            self.assertTrue(ws.connected)
            ws.close(status)
            self.assertFalse(ws.connected)
            self.assertEqual(value_before, counter.value,
                             'Connection error while closing with {}'.format(status))
Example #31
0
from websocket import create_connection
import json, datetime, time, string, random
import locale, calendar
locale.setlocale(locale.LC_ALL, '')


# Define a random string to send to the device
def randomString(stringLength=5):
    """Generate a random string of fixed length """
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))


ip = "192.168.2.130"
ws = create_connection("ws://" + ip + "/mca")

# Get Info
ws.send(
    "{\"m2m:rqp\":{\"op\":2,\"to\":\"/[0]/MNAE/\",\"fr\":\"/\",\"rqi\":\"" +
    randomString() + "\"}}")
js_function = json.loads(ws.recv())
function = js_function["m2m:rsp"]["pc"]["m2m:cnt"]["lbl"]

# device info
ws.send(
    "{\"m2m:rqp\":{\"op\":2,\"to\":\"/[0]/MNCSE-node/deviceInfo\",\"fr\":\"/\",\"rqi\":\""
    + randomString() + "\"}}")
js_deviceinfo = json.loads(ws.recv())
brand = js_deviceinfo["m2m:rsp"]["pc"]["m2m:dvi"]["man"]
model = js_deviceinfo["m2m:rsp"]["pc"]["m2m:dvi"]["mod"]
duty = js_deviceinfo["m2m:rsp"]["pc"]["m2m:dvi"]["dty"]
Example #32
0
import time
import cv2
import imutils
import msg_pb2
from websocket import create_connection

cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()

frame1 = imutils.resize(frame1, width=400)
prvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
prvs = cv2.GaussianBlur(prvs, (21, 21), 0)
avg = (cv2.GaussianBlur(prvs, (21, 21), 0)).copy().astype("float")

ws = create_connection("ws://127.0.0.1:8080/")

while True:
    ret, frame2 = cap.read()

    frame2 = imutils.resize(frame2, width=400)

    next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
    next = cv2.GaussianBlur(next, (21, 21), 0)
    cv2.accumulateWeighted(next, avg, 0.5)

    frameDelta = cv2.absdiff(next, cv2.convertScaleAbs(avg))
    thresh = cv2.threshold(frameDelta, 5, 255, cv2.THRESH_BINARY)[1]
    thresh = cv2.dilate(thresh, None, iterations=2)
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]

    for c in cnts:
Example #33
0
#! /usr/bin/env python
# -*- coding:utf-8 -*-

import time
from websocket import create_connection
ws = create_connection("ws://39.106.190.98:8002/")
print("Sending 'Hello, World'...")
for i in range(10, 20):
    time.sleep(10)
    ws.send("Hello, World %s" % i)
    print("Sent %s" % i)
    print("Receiving...%s" % i)
    result = ws.recv()
    print("Received '%s'" % result)
time.sleep(30)
# 关闭连接
ws.close()
Example #34
0
def terminate():
    global ws
    ws.close()
    print ('Bye\n')
    exit(0)

# MAIN

if  len(sys.argv) != 3:
    print ("\n Format: {} wss://ESserver:port/ password\n".format(sys.argv[0]))
    exit(1)

URL = sys.argv[1]
CONTROLPASSWD = sys.argv[2]

ws = create_connection(URL)
login()

functions = {
        '1': lambda: login(),
        '2': lambda: send_command(cmd='get'),
        '3':lambda: send_command(cmd='mute'),
        '4': lambda:send_command(cmd='unmute'),
        '5': lambda:restart(),
        '6': lambda:send_command(cmd='reset'),
        '7': lambda: edit(),
        '8': lambda:terminate()
        }

while True:
    print ("""
# -*- coding: utf-8 -*-
from websocket import create_connection
ws = create_connection("ws://localhost:444/websockets/uppercasemaker")
ws.send("hello\nahoj")
message = ws.recv()
print(message)
ws.close()
Example #36
0
input_graph = graphml.load_graphml(input_file)

import autonetkit.build_network as build_network
anm = build_network.initialise(input_graph)
anm = build_network.apply_design_rules(anm)



try:
	from websocket import create_connection
except ImportError:
	print "websocket-client package not installed"
else:
	autonetkit.update_http(anm)

	ws = create_connection("ws://localhost:8000/ws")
	ws.send("overlay_list")
	result =  ws.recv()
	expected = '{"overlay_list": ["bgp", "ebgp", "ebgp_v4", "ebgp_v6", "eigrp", graphics", "ibgp_v4", "ibgp_v6", "ibgp_vpn_v4", "input", "input_directed", "ip", "ipv4", "ipv6", "isis", "l3_conn", "ospf", "phy", "vrf"]}'
	assert(result == expected)

	overlay_id = "phy"
	ws.send("overlay_id=" + overlay_id)
	result =  ws.recv()
	with open(os.path.join(dirname, "expected_phy.json"), "r") as fh:
		expected = fh.read()

	assert(result == expected)
	ws.close()

	import autonetkit.console_script as console_script
Example #37
0
import tweepy
from dotenv import load_dotenv
import os
from websocket import create_connection
import json

load_dotenv()

ws = create_connection(os.environ["WEBSOCKET_SERVER_URL"])

auth = tweepy.OAuthHandler(os.environ["TWITTER_API_KEY"],
                           os.environ["TWITTER_API_SECRET_KEY"])
auth.set_access_token(os.environ["TWITTER_ACCESS_TOKEN"],
                      os.environ["TWITTER_ACCESS_TOKEN_SECRET"])
api = tweepy.API(auth)


class TwitterListener(tweepy.StreamListener):
    def on_status(self, status):
        ws.send(json.dumps(status._json))
        print(status._json)


twitterListener = TwitterListener()
myStream = tweepy.Stream(auth=api.auth, listener=twitterListener)
myStream.filter(track=['javascript', 'nodejs', 'python'])
Example #38
0
    def trace(api, wsapi, last, snapshot, app):
        """Trace application events.

        Invoking treadmill_trace with non existing application instance will
        cause the utility to wait for the specified instance to be started.

        Specifying already finished instance of the application will display
        historical trace information and exit status.

        Specifying only an application name will list all the instance IDs with
        trace information available.
        """
        # Disable too many branches.
        #
        # pylint: disable=R0912

        ctx['api'] = api
        ctx['wsapi'] = wsapi

        if '#' not in app:
            apis = context.GLOBAL.state_api(ctx['api'])
            url = '/trace/{app}'.format(app=urllib.quote(app))

            try:
                response = restclient.get(apis, url)
                trace_info = response.json()

            except restclient.NotFoundError:
                trace_info = {'name': app, 'instances': []}

            if not trace_info['instances']:
                print >> sys.stderr, '# Trace information does not exist.'
                return

            elif not last:
                for instanceid in sorted(trace_info['instances']):
                    cli.out('{app}#{instanceid}'.format(app=trace_info['name'],
                                                        instanceid=instanceid))
                return

            else:
                app = '{app}#{instanceid}'.format(
                    app=trace_info['name'],
                    instanceid=sorted(trace_info['instances'])[-1])

        apis = context.GLOBAL.ws_api(ctx['wsapi'])
        ws = None
        for api in apis:
            try:
                ws = ws_client.create_connection(api)
                _LOGGER.debug('Using API %s', api)
                break
            except socket.error:
                _LOGGER.debug(
                    'Could not connect to %s, trying next SRV '
                    'record', api)
                continue

        if not ws:
            click.echo('Could not connect to any Websocket APIs', err=True)
            sys.exit(-1)

        ws.send(
            json.dumps({
                'topic': '/trace',
                'filter': app,
                'snapshot': snapshot
            }))

        trace_printer = printer.AppTracePrinter()
        while True:
            reply = ws.recv()
            if not reply:
                break
            result = json.loads(reply)
            if '_error' in result:
                click.echo('Error: %s' % result['_error'], err=True)
                break

            event = events.AppTraceEvent.from_dict(result['event'])
            if event is None:
                continue

            trace_printer.process(event)

        ws.close()
    def task_thread(self):
        self.logger.info('数字货币:{} {} 数据获取开始时间:{}'.format(
            self.symbol, self.kline_type, time.strftime("%Y-%m-%d %H:%M:%S")))

        # 反复尝试建立websocket连接
        while True:
            try:
                # 是否需要使用代理(目前huobi不需要代理)
                proxy = self.exchange.get("proxy")
                # 获取建立websocket的请求链接
                socket_url = self.exchange.get("socket_url_spot")

                if proxy == "true":
                    ws = create_connection(socket_url,
                                           http_proxy_host="127.0.0.1",
                                           http_proxy_port=random.randint(
                                               8080, 8323))
                else:
                    ws = create_connection(socket_url)
                break
            except Exception as e:
                # self.logger.error(e)
                self.logger.info(
                    '数字货币: {} {} connect ws error, retry...'.format(
                        self.symbol, self.kline_type))
                time.sleep(1)

        logger.info("数字货币: {} {} connect success".format(
            self.symbol, self.kline_type))
        # 获取数据加密类型(gzip)
        utype = self.exchange.get("utype")

        # 发送了各币种的各k线的websocket请求
        print("req:", self.req)
        ws.send(self.req)

        # 获取数据:
        while True:
            try:
                # 设置 websocket 超时时间, 时间太久会导致 kline 一分钟没数据,因目前交易所采集稳定暂时不设置
                # ws.settimeout(30)
                # 接收websocket响应
                result = ws.recv()
                # 加密方式 gzip
                if utype == 'gzip':
                    try:
                        result = gzip.decompress(result).decode('utf-8')
                    except:
                        pass
                # 加密方式 deflate
                elif utype == "deflate":
                    decompress = zlib.decompressobj(-zlib.MAX_WBITS)
                    inflated = decompress.decompress(result)
                    inflated += decompress.flush()
                    result = inflated.decode()
                # 加密方式 未加密
                elif utype == "string":
                    pass

                # 如果websocket响应是 ping
                if result[:7] == '{"ping"':
                    # 则构建 pong 回复给服务器,保持连接
                    ts = result[8:21]
                    pong = '{"pong":' + ts + '}'
                    ws.send(pong)
                    # print(pong)
                    # ws.send(tradeStr_kline)
                else:
                    # self.logger.info(result)
                    self.save_result_redis(result)

            except Exception as e:
                logger.info(e)
                logger.info(result)
                logger.info("数字货币:{} {} 连接中断,reconnect.....".format(
                    self.symbol, self.kline_type))
                # 如果连接中断,递归调用继续
                self.task_thread()
Example #40
0
#!/usr/bin/env python

import json
import traceback

import websocket

SERVER = 'ws://127.0.0.1:8642'
AGENT = 'py-websockets-client'

ws = websocket.create_connection(SERVER + "/getCaseCount")
count = json.loads(ws.recv())
ws.close()

for case in range(1, count + 1):
    url = SERVER + '/runCase?case={0}&agent={1}'.format(case, AGENT)
    status = websocket.STATUS_NORMAL
    try:
        ws = websocket.create_connection(url)
        while True:
            opcode, msg = ws.recv_data()
            if opcode == websocket.ABNF.OPCODE_TEXT:
                msg.decode("utf-8")
            if opcode in (websocket.ABNF.OPCODE_TEXT,
                          websocket.ABNF.OPCODE_BINARY):
                ws.send(msg, opcode)
    except UnicodeDecodeError:
        # this case is ok.
        status = websocket.STATUS_PROTOCOL_ERROR
    except websocket.WebSocketProtocolException:
        status = websocket.STATUS_PROTOCOL_ERROR
#!/usr/bin/python
import time
import signal

from websocket import create_connection
ws = create_connection("ws://192.81.220.57:8880")

while True:
#   signal.alarm(1)
   time.sleep(60)
   ws.send("{\"message_type\":\"request\",\"type\":\"deduct_cash\"}")
   pass



result =  ws.recv()
print "Received '%s'" % result
ws.close()
Example #42
0
        cpuserial = "ERROR000000"
    return cpuserial


# serial number를 메시지로 보내기
def sendSerialNum():
    userID = getserial()

    ws.send("{\"fromDevice\":\"" + userID + "\"}")
    print(userID)
    return True


# 실행
# connect
ws = create_connection("ws://10.10.10.87:8080/name")
print("connecting....")

button = Button(21)

beforeSend = False
count = 0


def pressCheck():
    print("press check")
    global beforeSend, count

    while True:
        print("-----------------------" + str(count))
Example #43
0
def run(boxIP):
    number = 1
    indx1 = range(len(version1FileList))
    indx2 = range(len(version2FileList))
    while number <= 10000:
        # j = random.choice(list(indx))
        try:
            ws = create_connection(websocketIP, timeout=60)
            Login(boxIP, ws, number)
            DevFW = GetConfig(boxIP, ws, number)
            if version1 == DevFW:
                j = random.choice(list(indx2))
                print(
                    str(datetime.now()) +
                    ":——————————————————————————————%s盒子开始执行第:%d次升级,升级的版本是%s,升级的文件包是%s——————————————————————————————"
                    % (boxIP, number, version2, version2FileList[j][0]))
                Upgrade(boxIP, ws, version2FileList[j][0],
                        version2FileList[j][1], number)
                Upg_to_confirm(boxIP, version2FileList[j][2],
                               version2FileList[j][3], version2FileList[j][4],
                               number)
                endTime = datetime.now()
                print("%s盒子执行%s版本%s文件包进行升级共耗时:%s" %
                      (boxIP, version2, version2FileList[j][0],
                       str(endTime - startTime)))
                print(
                    str(endTime) +
                    ":——————————————————————————————%s盒子执行%s版本%s文件包升级MD5校验成功,第:%d次升级成功——————————————————————————————"
                    % (boxIP, version2, version2FileList[j][0], number))
                number += 1
                ws.close()
            else:
                j = random.choice(list(indx1))
                print(
                    str(datetime.now()) +
                    ":——————————————————————————————%s盒子开始执行第:%d次升级,升级的版本是%s,升级的文件包是%s——————————————————————————————"
                    % (boxIP, number, version1, version1FileList[j][0]))
                Upgrade(boxIP, ws, version1FileList[j][0],
                        version1FileList[j][1], number)
                Upg_to_confirm(boxIP, version1FileList[j][2],
                               version1FileList[j][3], version1FileList[j][4],
                               number)
                endTime = datetime.now()
                print("%s盒子执行%s版本%s文件包进行升级共耗时:%s" %
                      (boxIP, version1, version1FileList[j][0],
                       str(endTime - startTime)))
                print(
                    str(endTime) +
                    ":——————————————————————————————%s盒子执行%s版本%s文件包升级MD5校验成功,第:%d次升级成功——————————————————————————————"
                    % (boxIP, version1, version1FileList[j][0], number))
                number += 1
                ws.close()
        except Exception as e:
            errorMessage = str(
                datetime.now()
            ) + ":%s盒子第%d次升级出现异常执行getlog.sh保存日志至/usr/local/stor/logbak,:%s," % (
                boxIP, number, e)
            print(errorMessage)
            with open(autoUpdateFailLog, 'a') as f:
                f.write('\n')
                f.write(errorMessage)
                f.write('\n')
            traceback.print_exc(file=open(autoUpdateFailLog, 'a'))
            cmd_res(boxIP, port, username, password, finish, cmds[2])
            cmd_res(boxIP, port, username, password, finish, cmds[4])
            ws.close()
            time.sleep(300)
            number += 1
Example #44
0
 def connect(self):
     global token
     global headers
     self.socket = create_connection(socket_endpoint, header=headers)
import websocket

websocket.enableTrace(True)
ws = websocket.create_connection("ws://192.168.43.219:1880/ws/temperature/view")

while True:
	result = ws.recv()
	print "Received '%s'" % result
Example #46
0
 def _open_ws(self, platform: str = 'pc'):
     logger.debug('Opening websocket connection')
     return create_connection(f'wss://warframe.market/socket?platform={platform}', timeout=30, header=[f'Authorization: JWT {self.secret}'])
Example #47
0
 def _connect(self, **kwargs):
     self._ws = websocket.create_connection(**kwargs)
Example #48
0
 def connect_websocket(self):
     if not self.websocket:
         self.websocket = create_connection(self.url)
Example #49
0
			requests.delete(step3_url, timeout=10)
			### STEP 3 END

			print('waiting for a sec...')
			time.sleep(2)

			## STEP 4 START   WEBSOCKETS
			millis = int(round(time.time() * 1000))
			step4_url = 'http://' + tv_address + ':8000/socket.io/1/?t=' + str(millis)
			websocket_response = requests.get(step4_url, timeout=10)
			websocket_url = 'ws://' + tv_address + ':8000/socket.io/1/websocket/' + websocket_response.text.split(':')[0]

			time.sleep(1)
			print('sending KEY_VOLDOWN command!')
			aesLib = aes_lib.AESCipher(enc_key, session)
			connection = websocket.create_connection(websocket_url)
			time.sleep(0.35)
			connection.send('1::/com.samsung.companion')
			time.sleep(0.35)
			r = connection.send(aesLib.generate_command('KEY_VOLDOWN'))
			time.sleep(0.35)
			connection.close()
			print('sent')
			## STEP 4 END

			## STEP 5 WRITE CONFIG
			text_file = open(script_path+"/config", "w")
			text_file.write(sys.argv[2])
			text_file.write("\n%s" % enc_key)
			text_file.write("\n%s" % session)
			text_file.close()
def main():
    start_time = time.time()
    args = parse_args()
    if args.verbose > 1:
        websocket.enableTrace(True)
    options = {}
    if args.proxy:
        p = urlparse(args.proxy)
        options["http_proxy_host"] = p.hostname
        options["http_proxy_port"] = p.port
    if args.origin:
        options["origin"] = args.origin
    if args.subprotocols:
        options["subprotocols"] = args.subprotocols
    opts = {}
    if args.nocert:
        opts = {"cert_reqs": ssl.CERT_NONE, "check_hostname": False}
    if args.headers:
        options['header'] = list(map(str.strip, args.headers.split(',')))
    ws = websocket.create_connection(args.url, sslopt=opts, **options)
    if args.raw:
        console = NonInteractive()
    else:
        console = InteractiveConsole()
        print("Press Ctrl+C to quit")

    def recv():
        try:
            frame = ws.recv_frame()
        except websocket.WebSocketException:
            return websocket.ABNF.OPCODE_CLOSE, None
        if not frame:
            raise websocket.WebSocketException("Not a valid frame %s" % frame)
        elif frame.opcode in OPCODE_DATA:
            return frame.opcode, frame.data
        elif frame.opcode == websocket.ABNF.OPCODE_CLOSE:
            ws.send_close()
            return frame.opcode, None
        elif frame.opcode == websocket.ABNF.OPCODE_PING:
            ws.pong(frame.data)
            return frame.opcode, frame.data

        return frame.opcode, frame.data

    def recv_ws():
        while True:
            opcode, data = recv()
            msg = None
            if six.PY3 and opcode == websocket.ABNF.OPCODE_TEXT and isinstance(
                    data, bytes):
                data = str(data, "utf-8")
            if isinstance(data, bytes) and len(
                    data) > 2 and data[:2] == b'\037\213':  # gzip magick
                try:
                    data = "[gzip] " + str(gzip.decompress(data), "utf-8")
                except:
                    pass
            elif isinstance(data, bytes):
                try:
                    data = "[zlib] " + str(
                        zlib.decompress(data, -zlib.MAX_WBITS), "utf-8")
                except:
                    pass

            if isinstance(data, bytes):
                data = repr(data)

            if args.verbose:
                msg = "%s: %s" % (websocket.ABNF.OPCODE_MAP.get(opcode), data)
            else:
                msg = data

            if msg is not None:
                if args.timings:
                    console.write(str(time.time() - start_time) + ": " + msg)
                else:
                    console.write(msg)

            if opcode == websocket.ABNF.OPCODE_CLOSE:
                break

    thread = threading.Thread(target=recv_ws)
    thread.daemon = True
    thread.start()

    if args.text:
        ws.send(args.text)

    while True:
        try:
            message = console.read()
            ws.send(message)
        except KeyboardInterrupt:
            return
        except EOFError:
            time.sleep(args.eof_wait)
            return
Example #51
0
def reportHandler():

    content = request.get_json()
    submission_date = content['submission_date']
    latitude = content['latitude']
    longitude = content['longitude']
    comment = content['comment']
    images = content['images']

    print("Inserting new report")
    cursor = mydb.cursor()
    query = '''
		INSERT INTO report (status, submission_date, latitude, longitude, comment, FK_Researcher) 
		VALUES ('{}','{}','{}','{}','{}','{}');
	'''
    cursor.execute(
        query.format(1, submission_date, latitude, longitude, comment, 1))
    new_report_id = cursor.lastrowid
    print("New report : {}".format(new_report_id))
    mydb.commit()

    for image_path in images:

        print("Inserting in report_image")
        cursor = mydb.cursor()
        query = '''
			INSERT INTO report_image (path) 
			VALUES ('{}');
		'''
        cursor.execute(query.format(image_path))
        new_image_id = cursor.lastrowid
        print("New image : {}".format(new_image_id))
        mydb.commit()

        print("Inserting in report_to_image")
        cursor = mydb.cursor()
        query = '''
			INSERT INTO report_to_image (FK_Report,FK_Image) 
			VALUES ({},{});
		'''
        print("Values : {},{}".format(new_report_id, new_image_id))
        cursor.execute(query.format(new_report_id, new_image_id))
        mydb.commit()

    payload_dashboard = {
        "type": "NEW_REPORT",
        "new_report": {
            "id": new_report_id,
            "submission_date": submission_date,
            "images": images,
            "latitude": latitude,
            "longitude": longitude,
            "comment": comment,
            "status": 1
        }
    }
    ws = create_connection("ws://192.168.1.85:8080/")
    ws.send(json.dumps(payload_dashboard))
    ws.close()

    return "OK"
Example #52
0
def ws(url):
    webS = websocket.create_connection(url)
    resp = base64.b64decode(webS.recv())
    webS.close()
    return resp
Example #53
0
def run_commands(domain_id: str, user_profile_name: str):
    logger.info(f"[{domain_id}/{user_profile_name}] Generating presigned URL")
    # (This will only work for IAM-authenticated Studio domains)
    presigned_resp = smclient.create_presigned_domain_url(
        DomainId=domain_id,
        UserProfileName=user_profile_name,
    )
    sagemaker_login_url = presigned_resp["AuthorizedUrl"]

    # Login URL like https://d-....studio.{AWSRegion}.sagemaker.aws/auth?token=...
    # API relative to https://d-....studio.{AWSRegion}.sagemaker.aws/jupyter/default
    api_base_url = sagemaker_login_url.partition("?")[0].rpartition(
        "/")[0] + "/jupyter/default"

    # Need to make our requests via a session so cookies/etc persist:
    reqsess = requests.Session()
    logger.info(f"[{domain_id}/{user_profile_name}] Logging in")
    login_resp = reqsess.get(sagemaker_login_url)

    # If JupyterServer app only just started up, it may not be ready yet: In which case we need to wait for
    # it to start. Here we'll use the same 2sec /app polling logic as implemented by the SMStudio front-end
    # at the time of writing:
    if "_xsrf" not in reqsess.cookies:
        logger.info(
            f"[{domain_id}/{user_profile_name}] Waiting for JupyterServer start-up..."
        )
        app_status = "Unknown"
        base_url = sagemaker_login_url.partition("?")[0].rpartition("/")[0]
        while app_status not in {"InService", "Terminated"}:
            time.sleep(2)
            app_status = reqsess.get(
                f"{base_url}/app?appType=JupyterServer&appName=default").text
            logger.debug(f"Got app_status {app_status}")

        if app_status == "InService":
            logger.info(
                f"[{domain_id}/{user_profile_name}] JupyterServer app ready")
            ready_resp = reqsess.get(api_base_url)
        else:
            raise ValueError(
                f"JupyterServer app in unusable status '{app_status}'")

    logger.info(f"[{domain_id}/{user_profile_name}] Creating terminal")
    terminal_resp = reqsess.post(
        f"{api_base_url}/api/terminals",
        # The XSRF token is required on any state-changing request types e.g. POST/DELETE/etc, but seems
        # that it can be put either in header or query string.
        # For more information on this pattern, you can see e.g:
        # https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
        params={"_xsrf": reqsess.cookies["_xsrf"]},
    )
    terminal = terminal_resp.json()
    terminal_name = terminal["name"]  # Typically e.g. '1'.

    # Actually using a terminal (or notebook kernel) is done via websocket channels
    ws_base_url = "wss://" + api_base_url.partition(
        "://")[2] + "/terminals/websocket"
    cookies = reqsess.cookies.get_dict()

    logger.info(
        f"[{domain_id}/{user_profile_name}] Connecting to:\n{ws_base_url}/{terminal_name}"
    )
    ws = websocket.create_connection(
        f"{ws_base_url}/{terminal_name}",
        cookie="; ".join(["%s=%s" % (i, j) for i, j in cookies.items()]),
    )

    try:
        logger.info(
            f"[{domain_id}/{user_profile_name}] Waiting for setup message")
        setup = None
        while setup is not None:
            res = json.loads(ws.recv())
            if res[0] == "setup":
                setup = res[1]  # Just get {} in all my tests

        # Send commands one by one, waiting for each to complete and re-show prompt:
        prompt_exp = re.compile(PROMPT_REGEX, re.MULTILINE)
        for ix, c in enumerate(COMMAND_SCRIPT):
            ws.send(json.dumps(["stdin", c + "\n"]))
            # Assuming echo is on, stdin messages will be echoed to stdout anyway so no need to log

            while True:
                res = json.loads(ws.recv())
                # res[0] is the stream so will be e.g. 'stdout', 'stderr'
                # res[1] is the content
                logger.info(
                    f"[{domain_id}/{user_profile_name}] {res[0]}: {res[1]}")
                # You may want to apply some more RegExs here to log a little less verbosely, or actively
                # check for failure/success of your particular script.
                if res[0] == "stdout" and prompt_exp.search(res[1]):
                    break
                # No need to push too hard in recv()ing the tiniest possible chunks!
                time.sleep(0.1)

        logger.info(f"[{domain_id}/{user_profile_name}] Complete")
    finally:
        ws.close()
Example #54
0
 def sendWsMessage(data: JSONDict) -> JSONDict:
     ws = create_connection("ws://" + grid_address)
     ws.send(json.dumps(data))
     message = ws.recv()
     return json.loads(message)
Example #55
0
def send_ping_to_url(url):
    ws = create_connection(url, timeout=5)
    ws.send("ping")
    ws.close()
Example #56
0
from websocket import create_connection
import gzip
import time
import pandas as pd
import json
import talib as tb
import email_sender

kl1m_dict = {}
kl30m_dict = {}

if __name__ == '__main__':

    while (1):
        try:
            ws = create_connection("wss://api.huobipro.com/ws")
            break
        except:
            print('connect ws error,retry...')
            time.sleep(5)

    # 订阅 KLine 数据
    tradeStr = """{"sub": "market.nasusdt.kline.1min","id": "id10"}"""
    tradeStr_1day = """{"sub":"market.nasbtc.kline.1day"}"""
    # 请求 KLine 数据
    # tradeStr="""{"req": "market.ethusdt.kline.1min","id": "id10", "from": 1513391453, "to": 1513392453}"""

    # 订阅 Market Depth 数据
    # tradeStr="""{"sub": "market.ethusdt.depth.step5", "id": "id10"}"""

    # 请求 Market Depth 数据
Example #57
0
def request_configuration(hass, config, url, add_devices_callback):
    """Request configuration steps from the user."""
    configurator = get_component('configurator')
    if 'gpmdp' in _CONFIGURING:
        configurator.notify_errors(_CONFIGURING['gpmdp'],
                                   "Failed to register, please try again.")

        return
    from websocket import create_connection
    websocket = create_connection((url), timeout=1)
    websocket.send(
        json.dumps({
            'namespace': 'connect',
            'method': 'connect',
            'arguments': ['Home Assistant']
        }))

    # pylint: disable=unused-argument
    def gpmdp_configuration_callback(callback_data):
        """The actions to do when our configuration callback is called."""
        while True:
            from websocket import _exceptions
            try:
                msg = json.loads(websocket.recv())
            except _exceptions.WebSocketConnectionClosedException:
                continue
            if msg['channel'] != 'connect':
                continue
            if msg['payload'] != "CODE_REQUIRED":
                continue
            pin = callback_data.get('pin')
            websocket.send(
                json.dumps({
                    'namespace': 'connect',
                    'method': 'connect',
                    'arguments': ['Home Assistant', pin]
                }))
            tmpmsg = json.loads(websocket.recv())
            if tmpmsg['channel'] == 'time':
                _LOGGER.error('Error setting up GPMDP. Please pause'
                              ' the desktop player and try again.')
                break
            code = tmpmsg['payload']
            if code == 'CODE_REQUIRED':
                continue
            setup_gpmdp(hass, config, code, add_devices_callback)
            _save_config(hass.config.path(GPMDP_CONFIG_FILE), {"CODE": code})
            websocket.send(
                json.dumps({
                    'namespace': 'connect',
                    'method': 'connect',
                    'arguments': ['Home Assistant', code]
                }))
            websocket.close()
            break

    _CONFIGURING['gpmdp'] = configurator.request_config(
        hass,
        DEFAULT_NAME,
        gpmdp_configuration_callback,
        description=('Enter the pin that is displayed in the '
                     'Google Play Music Desktop Player.'),
        submit_caption="Submit",
        fields=[{
            'id': 'pin',
            'name': 'Pin Code',
            'type': 'number'
        }])
Example #58
0
#!/usr/bin/env python

import argparse
import json
import os

import websocket

_ws = websocket.create_connection('ws://127.0.0.1:5678')

_parser = argparse.ArgumentParser()
_parser.add_argument('-r',
                     dest='root',
                     required=True,
                     help='preload root directory')
_args = _parser.parse_args()

_filepaths = []
for _root, _dirs, _filenames in os.walk(_args.root):
    _filepaths.extend([os.path.join(_root, _filename)
                      for _filename in _filenames])

for _filepath in _filepaths:
    with open(_filepath, 'r') as _f:
        for _line in _f:
            _ws.send(_line.rstrip())
Example #59
0
#from __future__ import print_function

import sys
sys.path.append("..")
import websocket

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.create_connection("ws://echo.websocket.org/")
    print("Sending 'Hello, World'...")
    ws.send("Hello, World")
    print("Sent")
    print("Receiving...")
    result = ws.recv()
    print("Received '%s'" % result)
    ws.close()
Example #60
0
			print(drug)	
			if a<1:	
				if drug["href"].startswith("/wiki"):	
					a+=1	
					drug_info = {"title": drug["title"], "link": drug["href"]}	
					title=drug_info['title']	
					link=drug_info['link']	
					url=title+':\n'+'* http://psychonaut3z5aoz.onion'+link	
					_send_msg(url)	

def commands():	
	while True:	
		_input=json.loads(ws.recv())	
		if _input['cmd']=='chat' and '`wttr ' in _input['text']:	
			_send_msg('be patient tor being tor')	
			wttr(_input)	
		elif _input['cmd']=='chat' and '`msearch ' in _input['text']:	
			_send_msg('be patient tor being tor')	
			_search_mtube(_input)	
		elif _input['cmd']=='chat' and '`search ' in _input['text']:	
			_send_msg('be patient tor being tor')	
			_search_tube(_input)	
		elif _input['cmd']=='chat' and '`drug ' in _input['text']:	
			_send_msg('$\\tiny\\text{be patient tor being tor}$')	
			drug_wiki(_input)	
##########		connections & commands/logs			##########	
ws = websocket.create_connection('wss://hack.chat/chat-ws')	
_send({"cmd": "join", "channel": channel, "nick": nick})	
commands=threading.Thread(target=commands).start()	
msg = threading.Thread(target=_send_msg_in_chat).start()