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)
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)
Beispiel #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')
Beispiel #4
0
def push_usage():
    """
    每隔三秒推送一次 CPU 内存和磁盘的使用状况,
    """

    while client.send_usaged:
        # 获取当前 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")
        diskusage = client.get_diskusage()
        # 获取时间
        t = get_timer()
        # 推送数据
        data = {
            "cpu": cpus,
            "men": [memory_usage, memory_size],
            "disk": diskusage,
            'timer': t
        }
        data = json.dumps(data)
        try:
            client.sock.send(('[::usage]%s' % data).encode())
        except OSError:
            client.send_usaged = False
            break
        # 阻塞2秒
        socketio.sleep(2)
Beispiel #5
0
 def defined(self,
             data: dict,
             status: int = StatusOK,
             headers: dict = None) -> jsonify:
     self.data = data
     self.data["data"] = get_service_info()
     self.data['timer'] = get_timer()
     return jsonify(self.data), status, headers
Beispiel #6
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')
 def write(self, message: str, type: str = "INFO"):
     fo = open(self.__get_path(), "a")
     logitem = get_timer() + ' [{}]: '.format(type)
     logitem += message
     fo.write(logitem)
     fo.close()
Beispiel #8
0
 def __init__(self):
     # 初始化数据
     self.data = {
         "timer": get_timer(),
     }
Beispiel #9
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')