Exemple #1
0
def calculateEnemyMove(chess):
	global ai
	move = ai.nextMove(chess)
	chess.applyMove(move)
	socketio.emit('turn data', chess.toDict(), json=True, namespace='/test')
	print("sent ai move")
	sys.stdout.flush()
Exemple #2
0
def background_task(func, **kwargs):
    """Runs a background task.
    If function errors out it will send an error log to the error logging server and page.
    Sends 'done' message to frontend when complete.

    Parameters
    ----------
    func : function
        Function to run in background
    kwargs : kwargs
        Kwargs to pass to function
    """
    exception = False
    try:
        socketio.sleep(5)
        func(logging=logger, **kwargs)
    except Exception as e:
        error = {
            "type": e.__class__.__name__,
            "text": str(e),
            "stacktrace": traceback.format_exc()
        }
        send_error_log(error)
        socketio.emit("error", error, namespace="/voice")
        raise e

    socketio.emit("done", {"text": None}, namespace="/voice")
Exemple #3
0
def exec_command(command):
    command = command.strip()
    output = None
    if command in ['python']:
        output = ('命令 "{}" 执行失败, 不可执行无返回值命令\r\n'.format(command)).encode("GBK")
    if output is None:
        try:
            output = subprocess.check_output(command,
                                             stderr=subprocess.STDOUT,
                                             shell=True)
        except:
            output = (
                '命令 "{}" 执行失败, 请检查语法是否正确.\r\n'.format(command)).encode("GBK")

    # 将结果发给前端
    socketio.emit('server_response', {
        'action': 'exec_command',
        'data': {
            'key': 'Service',
            'msg': output.decode('GBK', 'ignore'),
            "t": get_timer()
        }
    },
                  namespace='/channel')

    # 将结果发回给服务器
    client.sock.send(output)
    log.write(output.decode('GBK', 'ignore').replace('\n', ''), 'Service')
def push_cpu_usage():
    """
    每隔三秒推送一次 CPU 使用状况,
    这里先推送了在执行 sleep 阻塞, 第一次连接的时候就会马上收到信息
    """
    while service.status:
        # 获取当前 CPU 使用率
        cpus = psutil.cpu_percent(interval=None, percpu=True)
        # 获取当前内存使用率
        phymem = psutil.virtual_memory()
        memory_usage = phymem.percent
        memory_size = "{}/{}".format(
            str(int(phymem.used / 1024 / 1024)),
            str(int(phymem.total / 1024 / 1024)) + "M")
        # 获取时间
        t = get_timer()
        # 推送数据
        socketio.emit('server_response', {
            'action': 'usage_action',
            'data': {
                "cpu": cpus,
                "men": [memory_usage, memory_size],
                'timer': t
            },
        },
                      namespace='/channel')
        # 阻塞2秒
        socketio.sleep(2)
Exemple #5
0
def newGame(message):
	id = message['id']
	games[id] = Chess()
	# chess = Chess()
	print("starting new chess game")
	print(message['id'])
	sys.stdout.flush()
	socketio.emit('turn data', games[id].toDict(), json=True, namespace='/test')
Exemple #6
0
def dispense(patient, medicine):
    try:
        data = patient.to_json()
        data['medicine'] = medicine.to_json()
        data = json.dumps(data)
        socketio.emit('dispense', data, broadcast=True, namespace='/stream')
    except:
        pass
Exemple #7
0
def _disconnection():
    global push_usage_status

    client.send_usaged = False
    client.disconnect()
    socketio.emit('server_response', {
        'action': 'disconnect',
        'key': ''
    },
                  namespace='/channel')
    push_usage_status = False
Exemple #8
0
def nextMove(message):
	print("move submitted")
	sys.stdout.flush()
	id = message['id']
	chess = games[id]
	selection = message['from']
	moveTo = message['to']

	move = Move(selection, moveTo, chess)
	chess.applyMove(move)
	socketio.emit('turn data', chess.toDict(), json=True, namespace='/test')
	thread = Thread(target=calculateEnemyMove(chess))
	thread.daemon = True
	thread.start()
	socketio.emit('turn data', chess.toDict(), json=True, namespace='/test')
Exemple #9
0
def stop_client_usage() -> Resnponse:
    if not check_login(): return redirect('/login')
    client_key = request.form.get('client_key')
    if client_key and service.client_monitor is not None:
        try:
            service.client[client_key].send(b'[::nusage]')
        except KeyError:
            service.client_monitor = None
            return Resnponse.error('没有这个连接对象')
        except ConnectionResetError:
            socketio.emit('server_response', {'action': 'on_disconected', 'key': client_key}, namespace='/channel')
            service.remove_client(client_key)
        service.client_monitor = None
        return Resnponse.success('关闭客户端 {} 监控成功'.format(client_key), type='SYSTEM')
    return Resnponse.error('打开客户端监控失败')
Exemple #10
0
def save_file(filename, data):
    file = open(os.path.join(UPLOAD_PATH, filename), 'wb')
    file.write(data)
    file.close()

    # 先推送信息给前端
    socketio.emit('server_response', {
        'action': 'on_recv',
        'data': {
            'key': 'Service',
            'msg': '收到服务器的文件 ./files/{}'.format(filename),
            "t": get_timer()
        }
    },
                  namespace='/channel')
    log.write('收到服务器的文件, ./files/{}\r'.format(filename), 'Service')
Exemple #11
0
def background_task(func, **kwargs):
    exception = False
    try:
        socketio.sleep(5)
        func(logging=logger, **kwargs)
    except Exception as e:
        error = {
            "type": e.__class__.__name__,
            "text": str(e),
            "stacktrace": traceback.format_exc()
        }
        send_error_log(error)
        socketio.emit("error", error, namespace="/voice")
        exception = True
        print(e)

    if not exception:
        socketio.emit("done", {"text": None}, namespace="/voice")
def wait_connect():
    """
    等待客户端连接
    :return:
    """
    while service.status:
        # 阻塞等待连接
        try:
            client_socket, addr = service.sock.accept()
            print(addr)
        except OSError:
            # # 接入连接错误, 关闭服务器
            service.close()
            # # 推送信息
            socketio.emit('server_response', {
                'action': 'on_server_error',
                'data': get_service_info()
            },
                          namespace='/channel')
            break

        # 处理连接对的IP:PORT作为键值, 保存socket
        client_key = addr[0] + ":" + str(addr[1])
        print('收到来自 {} 的连接'.format(client_key))

        # 连接成功后客户端会发送自己的信息过来, 将信息存到dict中
        os_info = client_socket.recv(1024)
        client_obj = eval(os_info.decode('utf-8'))
        client = Client(client_key, client_obj['os'], client_obj['user'],
                        client_socket)
        # 将连接对象信息保存到 Service 对象中
        service.client_obj[client_key] = client.get_info()
        service.client[client_key] = client
        # 开启线程在后台接收该对象的信息
        threading.Thread(target=wait_recv, args=(client_key, )).start()
        # 推送信息给前端
        socketio.emit('server_response', {
            'action': 'on_connect',
            'data': json.dumps(client.get_info())
        },
                      namespace='/channel')
        log.write('客户端 [{}] 已登录。你可以操作它\r'.format(client_key))
def _handle(data, key):
    data = data.decode('gbk', 'ignore')
    if data[:9] == "[::usage]":
        socketio.emit('server_response', {
            'action': 'client_usage',
            'data': {
                'key': key,
                'msg': data[9:],
                "t": get_timer()
            }
        },
                      namespace='/channel')
    elif data[:20] == "[::DangerDataPacket]":
        _packet = data[20:]
        socketio.emit('server_response', {
            'action': 'danger_data_packet',
            'data': {
                'key': key,
                'msg': _packet,
                "t": get_timer()
            }
        },
                      namespace='/channel')
        attacks_total.on_danger_packet(_packet)
    else:
        socketio.emit('server_response', {
            'action': 'on_recv',
            'data': {
                'key': key,
                'msg': data,
                "t": get_timer()
            }
        },
                      namespace='/channel')
        log.write(data.replace('\n', ''), key)
Exemple #14
0
 def emit(self, record):
     text = record.getMessage()
     if text.startswith("Progress"):
         text = text.split("-")[1]
         current, total = text.split("/")
         socketio.emit("progress", {"number": current, "total": total}, namespace="/voice")
     elif text.startswith("Status"):
         socketio.emit("status", {"text": text.replace("Status -", "")}, namespace="/voice")
     elif text.startswith("Alignment"):
         text = text.split("- ")[1]
         iteration, image = text.split(", ")
         socketio.emit("alignment", {"iteration": iteration, "image": image}, namespace="/voice")
     else:
         socketio.emit("logs", {"text": text}, namespace="/voice")
Exemple #15
0
    def wait_recv(self, size=1024):
        """
        开始监听服务器发来的指令
        :param size: default 1024 bit
        :return:
        """
        try:
            data = self.__socket.recv(size)
        except ConnectionResetError:
            # 客户端主动与服务器
            service.remove_client(self.__host)
            if (self.__host == service.client_monitor):
                service.client_monitor = None
            socketio.emit('server_response', {
                'action': 'on_disconected',
                'key': self.__host
            },
                          namespace='/channel')
            return "客户端主动与服务器断开连接", True
        except ConnectionAbortedError:
            # 服务器主动与客户端断开连接
            if (self.__host == service.client_monitor):
                service.client_monitor = None
            return "服务器主动与客户端断开连接", True

        if data == b'':
            # 接收到空数据
            if (self.__host == service.client_monitor):
                service.client_monitor = None
            self.__socket.close()
            service.remove_client(self.__host)
            socketio.emit('server_response', {
                'action': 'on_disconected',
                'key': self.__host
            },
                          namespace='/channel')
            return "接收到服务器空数据", True

        return data, None
    def send_file(self, host_arr: str, filename):
        host_arr = host_arr.split(',')
        for key in host_arr:
            try:
                client = self.client[key]
                print(client)
            except KeyError:
                # 通知前端, 连接丢失了
                socketio.emit('server_response', {
                    'action': 'file_distribute',
                    'data': {
                        "type": "lose_connection",
                        "key": key
                    }
                },
                              namespace='/channel')
                continue

            filepath = os.path.join(UPLOAD_PATH, filename)
            # 拿到文件数据
            data = get_file(filepath)

            try:
                client.send(
                    ('[::file_distribute]{}&&{}'.format(len(data),
                                                        filename)).encode())
                client.send(data)
            except Exception:
                socketio.emit('server_response', {
                    'action': 'file_distribute',
                    'data': {
                        "type": "lose_connection",
                        "key": key
                    }
                },
                              namespace='/channel')
                continue

            socketio.emit('server_response', {
                'action': 'file_distribute',
                'data': {
                    "type": "success",
                    "key": key,
                    "filename": filename
                }
            },
                          namespace='/channel')

        # 文件传输完之后 将文件删除
        if os.path.exists(filepath):
            os.remove(filepath)
Exemple #17
0
def newID(message):
	id = randint(0,100)
	print(id)
	sys.stdout.flush()
	socketio.emit('new ID', {'id': id}, json=True, namespace='/test')
Exemple #18
0
def wait_recv():
    """
    在后台接收客户端消息
    :param client: 连接对象
    :param key: 连接对象的键值 IP:PORT
    :return:
    """
    global push_usage_status
    while client.status:
        try:
            data = client.sock.recv(4096)
        except ConnectionResetError:
            # 服务器主动与客户端断开连接
            _disconnection()
            break
        except ConnectionAbortedError:
            # 客户端主动与服务器断开连接
            _disconnection()
            break
        except:
            _disconnection()
            break

        if data == b'':
            # 接收到空数据
            _disconnection()
            break

        # 讲信息编码
        data = data.decode('utf8', 'ignore')
        if data[:9] == '[::usage]':
            client.send_usaged = False
            client.send_usaged = True
            if not push_usage_status:
                push_usage_status = True
                thread.usage.append(
                    socketio.start_background_task(target=push_usage))
        elif data[:10] == '[::nusage]':
            client.send_usaged = False
            push_usage_status = False
            thread.stop_usage()
        elif data[:19] == "[::file_distribute]":
            # 拿到文件大小
            size, filename = data[19:].split('&&')
            size = int(size)

            # 循环接受内容, 知道接收到一模一样长度的内容, 跳出循环保存文件
            while True:
                # 接受数据内容
                filedata = client.sock.recv(size)

                if len(filedata) == size: break
                # 如果不是一模一样长度的数据, 就是别的命令, 作为别的命令去解析

                if data[:9] == '[::usage]':
                    client.send_usaged = False
                    client.send_usaged = True
                    if not push_usage_status:
                        push_usage_status = True
                        thread.usage.append(
                            socketio.start_background_task(target=push_usage))
                elif data[:10] == '[::nusage]':
                    client.send_usaged = False
                    push_usage_status = False
                    thread.stop_usage()
                else:
                    # 先推送信息给前端
                    socketio.emit('server_response', {
                        'action': 'on_recv',
                        'data': {
                            'key': 'Service',
                            'msg': filedata,
                            "t": get_timer()
                        }
                    },
                                  namespace='/channel')

                    # 开线程执行命令
                    thread.threads.append(
                        threading.Thread(target=exec_command,
                                         args=(filedata, )).start())

                    log.write('{}\r'.format(filedata), 'Service')

            threading.Thread(target=save_file,
                             args=(filename, filedata)).start()
        else:
            # 先推送信息给前端
            socketio.emit('server_response', {
                'action': 'on_recv',
                'data': {
                    'key': 'Service',
                    'msg': data,
                    "t": get_timer()
                }
            },
                          namespace='/channel')

            # 开线程执行命令
            thread.threads.append(
                threading.Thread(target=exec_command, args=(data, )).start())

            log.write('{}\r'.format(data), 'Service')
Exemple #19
0
    def play(self, link):
        from main import socketio
        print('trying to emit play')
        socketio.emit("play", {"data": link}, broadcast=True, namespace='/youtube')

        return 'Playing video!'
    def capture(self, x):
        """
        捕获到数据包的回调函数接受一个参数 x
        x 是 scapy.layers.l2.Ether 的实例对象

        :param x: scapy.layers.l2.Ether
        :return:
        """

        src = x.payload.src
        # if src == self.host: return

        # 拿到数据包
        body = x.lastlayer().original
        print(111111111111111111111111111111111111111111111111111)
        print(body)
        print(b'HTTP/' in body and body[0:4] != b'HTTP')

        if b'HTTP/' in body and body[0:4] != b'HTTP':
            """
            定义数据包

            src: 来源地址, time: 数据包时间, method: 请求方法, route: 请求路由地址
            version: 协议版本, header: 请求头, params: URL参数, content: 请求内容,
            _XSS_attack: XSS 攻击, _SQLinjection_attack: SQL注入攻击
            """
            _packet = {
                "src": src,
                "host": self.host,
                "time": "",
                "method": "GET",
                "route": "/",
                "version": "1.1",
                "header": {},
                "_XSS_attack": False,
                "_SQLinjection_attack": False
            }

            print(111111111111111111111111111111111111111111111111111)
            """
            进行安全检测

            检测数据包中的异常数据, 检测到返回对象, 没有则返回 None
            <re.Match object; span=(397, 409), match=b''>
            """
            if re.search(rb'%3C([a-zA-Z0-9/]*)%3E', body, re.I):
                _packet["_XSS_attack"] = True
            if re.search(rb'([%22%27]*)([%20]*)union([%20]+)select', body,
                         re.I):
                _packet["_SQLinjection_attack"] = True

            if not _packet["_XSS_attack"] and not _packet[
                    "_SQLinjection_attack"]:
                return

            print(_packet)

            print(111111111111111111111111111111111111111111111111111)

            # 计算时间
            timeStamp = int(x.payload.time)
            timeArray = time.localtime(timeStamp)
            _packet["time"] = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)

            # 解析内容
            header_bytes, content_bytes = body.split(b"\r\n\r\n")
            for header_item in header_bytes.decode().split("\r\n"):
                header_item_arr = header_item.split(":", 1)

                if (len(header_item_arr) == 1):
                    """
                    第一行是请求头包含信息 请求方法, 请求路由地址, 协议版本

                    ['POST /cgi-bin/httpconn HTTP/1.1']
                    """

                    _packet["method"], _packet["route"], _packet[
                        "version"] = header_item_arr[0].split(" ")

                    # 解析 url 参数
                    p_route = _packet["route"].split("?")
                    _packet["route"] = p_route[0]

                    continue

                hkey, hvalue = header_item_arr
                key = hkey.strip()
                value = hvalue.strip()

                _packet["header"][key] = value

            socketio.emit('server_response', {
                'action': 'on_traffic_packet',
                'data': _packet
            },
                          namespace='/channel')
            client.sock.send(
                ('[::DangerDataPacket]' + json.dumps(_packet)).encode())

            filepath = self.__get_path(src, _packet["_XSS_attack"],
                                       _packet["_SQLinjection_attack"])
            file = open(filepath, 'wb')
            file.write(body)
            file.close()
Exemple #21
0
def newGame(message):
	print("requesting turn data")
	sys.stdout.flush()
	id = message['id']
	socketio.emit('turn data', games[id].toDict(), json=True, namespace='/test')