Пример #1
0
    def start_sort_terminal(self, data):
        group_uuid = data.get("group_uuid", "")
        start_num = data.get("index_start")

        if not (group_uuid and start_num) or not isinstance(start_num, int):
            logger.error("terminal sort number error: param error")
            return get_error_result("ParamError")

        # 判断组的存在
        group = self.get_object_by_uuid(YzyGroup, group_uuid)
        if not group:
            logger.error("terminal sort number error: %s group not exist" %
                         group_uuid)
            return get_error_result("TerminalWebGroupNotExist")

        req_data = {
            "handler": "WebTerminalHandler",
            "command": "terminal_order",
            "data": {
                "group_uuid": group_uuid,
                "start_num": start_num
            }
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        msg = "分组 %s 终端排序" % group.name
        insert_operation_log(msg, ret["msg"])
        if ret.get("code", -1) != 0:
            logger.error("terminal update name fail")
            return ret

        logger.info("terminal sort number success!!! %s" % group.name)
        return ret
Пример #2
0
    def delete_terminal(self, data):
        """ 删除终端 """
        try:
            mac_list, name_list = self.get_terminal_mac_name_list(data)
        except Exception as e:
            logger.error("", exc_info=True)
            return get_error_result("ParamError")

        mac_list_str = ",".join(mac_list)
        # 提交终端服务接口
        req_data = {
            "handler": "WebTerminalHandler",
            "command": "delete",
            "data": {
                "mac_list": mac_list_str,
            }
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        msg = "删除终端 %s" % "/".join(name_list)
        insert_operation_log(msg, ret["msg"])
        if ret.get("code", -1) != 0:
            logger.error("terminal close fail: %s" % mac_list_str)
            return get_error_result("TerminalCloseOperateError")

        logger.info("terminal delete success!!! %s" % mac_list_str)
        return get_error_result("Success")
Пример #3
0
    def delete_user(self, user):
        logger.info("delete group name:%s, user:%s", user['user_name'],
                    user['uuid'])
        qry = personal_model.YzyGroupUser.objects.filter(
            uuid=user['uuid'], deleted=False).first()
        if not qry:
            logger.info("delete group user failed, it is not exists")
            return get_error_result("GroupUserNotExists",
                                    user_name=user['user_name'])
        ret = server_post("/api/v1/group/user/delete", {"uuid": user['uuid']})
        if ret.get('code') != 0:
            logger.info("delete group user failed:%s", ret['msg'])
            return ret
        else:
            if qry.mac:
                # 提交终端服务接口
                req_data = {
                    "handler": "WebTerminalHandler",
                    "command": "user_logout",
                    "data": {
                        "mac_list": qry.mac,
                    }
                }
                ret = terminal_post("/api/v1/terminal/task", req_data)
                if ret.get("code", -1) != 0:
                    logger.error("terminal send user logout fail: %s" %
                                 qry.mac)

            logger.info("delete group user success, name:%s, uuid:%s",
                        user['user_name'], user['uuid'])
        return get_error_result("Success", {"success_num": 1, "failed_num": 0})
Пример #4
0
    def update_setup_terminal(self, data):
        """更新终端配置
        {
            "handler": "WebTerminalHandler",
            "command": "set_terminal",
            "data": {
                "mac_list": "00-50-56-C0-00-08,00-50-56-C0-00-07,00-50-56-C0-00-06",
                "mode": {
                    "show_desktop_type": 0,
                    "auto_desktop": 1,
                    "open_strategy": true,
                    "close_desktop_strategy": false,
                    "close_terminal_strategy": true
                },
                "program": {
                    "screen_resolution": "1024*768",
                    "server_ip": "172.16.1.33",
                    "show_modify_user_passwd": true,
                    "terminal_setup_passwd": "111111"
                },
                "windows": {
                    "window_mode": 2,
                    "goto_local_desktop": 5,
                    "goto_local_auth": true,
                    "show_local_button": false,
                    "goto_local_passwd": "123456"
                }
            }
        }
        """
        try:
            mac_list, name_list = self.get_terminal_mac_name_list(data)
        except Exception as e:
            logger.error("", exc_info=True)
            return get_error_result("ParamError")

        setup_info = data.get("setup_info", {})
        if not self.check_setup_info(setup_info):
            return get_error_result("TerminalSetupInfoParamError")
        data = {"mac_list": ",".join(mac_list)}
        data.update(setup_info)
        req_data = {
            "handler": "WebTerminalHandler",
            "command": "set_terminal",
            "data": data
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        msg = "更新终端配置 %s" % "/".join(name_list)
        insert_operation_log(msg, ret["msg"])
        if ret.get("code", -1) != 0:
            logger.error("terminal update setup info fail")
            return ret

        logger.info("terminal update setup info success!!!")
        return get_error_result("Success")
Пример #5
0
    def upgrade_terminal(self, data):
        """ 终端升级 """
        all = data.get("all")
        group_uuid = data.get("group_uuid")
        upgrade_uuid = data.get("upgrade_uuid")
        upgrade = self.get_object_by_uuid(YzyTerminalUpgrade, upgrade_uuid)
        if all:
            terminals = self.get_all_object(YzyTerminal,
                                            {"group_uuid": group_uuid})
            mac_list = list()
            name_list = list()
            for terminal in terminals:
                mac = terminal.mac
                if upgrade.platform == terminal.platform:
                    if mac not in mac_list:
                        mac_list.append(mac)
                    name_list.append(terminal.name)
        else:
            try:
                mac_list, name_list = self.get_terminal_mac_name_list(data)
            except Exception as e:
                logger.error("", exc_info=True)
                return get_error_result("ParamError")
            terminals = self.get_all_object(YzyTerminal, {"mac": mac_list})
            for terminal in terminals:
                if terminal.platform.lower() != upgrade.platform.lower():
                    mac_list.remove(terminal.mac)
        if not mac_list:
            logger.error("NO need upgrade terminals")
            return get_error_result("TerminalUpgradeNotNeedError")

        upgrade_pig = upgrade.path
        if not os.path.exists(upgrade_pig):
            return get_error_result("TerminalUpgradeFileError")

        req_data = {
            "handler": "WebTerminalHandler",
            "command": "update_program",
            "data": {
                "mac_list": ",".join(mac_list),
                "program_file_name": os.path.basename(upgrade_pig)
            }
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        # msg = "移动终端: %s 到 %s 分组" % ("/".join(name_list), group.name)
        # insert_operation_log(msg, ret["msg"])

        if ret.get("code", -1) != 0:
            logger.error("terminal upgrade error: %s" % ret["msg"])
            return ret

        logger.info("terminal upgrade success!!! %s" % ("/".join(name_list)))
        return get_error_result("Success")
Пример #6
0
    def update_name_terminal(self, data):
        """ 修改终端名称 """
        terminals = data.get("terminals", [])
        perfix = data.get("prefix", "")
        postfix = data.get("postfix", "")
        postfix_start = data.get("postfix_start", "")
        use_terminal_id = data.get("use_terminal_id", False)
        if not (terminals and perfix and postfix and postfix_start):
            logger.error("update terminals name param error")
            return get_error_result("ParamError")

        name_list = list()
        _data = dict()
        if use_terminal_id:
            for terminal in terminals:
                mac = terminal["mac"]
                name = terminal["name"]
                terminal_id = terminal["terminal_id"]
                _s = "%" + "0%sd" % postfix
                _n = perfix.upper() + "-" + _s % int(terminal_id)
                _data[mac] = _n
                if name not in name_list:
                    name_list.append(name)
        else:
            for terminal in terminals:
                mac = terminal["mac"]
                name = terminal["name"]
                _s = "%" + "0%sd" % postfix
                _n = perfix.upper() + "-" + _s % postfix_start
                _data[mac] = _n
                postfix_start += 1
                if name not in name_list:
                    name_list.append(name)

        req_data = {
            "handler": "WebTerminalHandler",
            "command": "modify_terminal_name",
            "data": _data
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        msg = "修改终端名称 %s" % "/".join(name_list)
        insert_operation_log(msg, ret["msg"])
        if ret.get("code", -1) != 0:
            logger.error("terminal update name fail")
            return ret

        logger.info("terminal update name success!!!")
        return get_error_result("Success")
Пример #7
0
    def end_sort_terminal(self, data):
        """ 终止排序 """
        batch_num = data.get("batch_num", None)
        group_uuid = data.get("group_uuid", None)
        if not batch_num or not group_uuid:
            return get_error_result("ParamError")

        req_data = {
            "handler": "WebTerminalHandler",
            "command": "cancel_terminal_order",
            "data": {
                "group_uuid": group_uuid,
                "batch_num": batch_num
            }
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        msg = "停止终端排序: %s" % batch_num
        insert_operation_log(msg, ret["msg"])
        if ret.get("code", -1) != 0:
            logger.error("terminal update name fail")
            return ret

        logger.info("terminal stop sort number success!!! %s" % batch_num)
        return ret
Пример #8
0
    def export_log_terminal(self, data):
        """ 终端日志导出 """
        try:
            mac_list, name_list = self.get_terminal_mac_name_list(data)
            if not mac_list:
                raise Exception("terminals not exist")
        except Exception as e:
            logger.error("", exc_info=True)
            return get_error_result("ParamError")

        if len(mac_list) > 5:
            logger.error("terminal log export error: %s too much!" %
                         (len(mac_list)))
            return get_error_result("TerminalLogFiveLimitError")
        success_num = 0
        fail_num = 0
        today_date = datetime.datetime.now()
        start_date = (today_date +
                      datetime.timedelta(days=-7)).strftime("%Y-%m-%d")
        c_mac_list = copy.deepcopy(mac_list)
        for i in mac_list:
            terminal = YzyTerminal.objects.filter(deleted=False, mac=i).first()
            if terminal.status == '0':
                c_mac_list.remove(i)
                fail_num += 1
                continue
            file_name = "%s_%s.ok" % (i, start_date)
            file_path = os.path.join(constants.TERMINAL_LOG_PATH, file_name)
            if os.path.exists(file_path):
                os.remove(file_path)
        targe_file = os.path.join(
            constants.TERMINAL_LOG_PATH,
            "%s.tar.gz" % today_date.strftime("%Y-%m-%d"))
        if os.path.exists(targe_file):
            os.remove(targe_file)
        if len(c_mac_list) == 0:
            success_num += len(c_mac_list)
            ret = get_error_result("Success")
            ret['msg'] = '批量导出日志' + ret['msg'] + ': {}, 失败: {}'.format(
                success_num, fail_num)
            return ret
        req_data = {
            "handler": "WebTerminalHandler",
            "command": "get_log_file",
            "data": {
                "mac_list": ",".join(c_mac_list),
                "start_date": start_date,
                "end_date": today_date.strftime("%Y-%m-%d")
            }
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        msg = "导出终端日志: %s" % "/".join(name_list)
        insert_operation_log(msg, ret["msg"])
        if ret.get("code", -1) != 0:
            logger.error("terminal log export error: %s" % ret["msg"])
            return ret

        logger.info("terminal export log success!!! %s" %
                    ("/".join(name_list)))
        success_num += len(c_mac_list)
        ret = get_error_result("Success")
        ret['msg'] = '批量导出日志' + ret['msg'] + ': {}, 失败: {}'.format(
            success_num, fail_num)
        return ret
Пример #9
0
    def modify_ip_terminal(self, data):
        """ 按序重排ip
        """
        terminals = data.get("terminals", [])

        modify_ip_method = data.get("modify_ip_method")
        group_uuid = data.get("group_uuid", "")
        if modify_ip_method == "dhcp":
            req_data = {
                "handler": "WebTerminalHandler",
                "command": "modify_ip",
                "data": {
                    "group_uuid": group_uuid,
                    "modify_ip_method": modify_ip_method,
                }
            }
            logger.debug("Use dhcp to modify group's %s terminals" %
                         group_uuid)
            ret = terminal_post("/api/v1/terminal/task", req_data)
            return ret

        start_ip = data.get("start_ip")
        netmask = data.get("netmask")
        gateway = data.get("gateway")
        dns1 = data.get("dns1")
        dns2 = data.get("dns2")
        yzy_group = self.get_object_by_uuid(YzyGroup, uuid=group_uuid)
        if not yzy_group:
            return get_error_result("ParameterError")
        if not is_ip_addr(start_ip):
            return get_error_result("IpAddressError")
        if not is_netmask(netmask)[0]:
            return get_error_result("SubnetMaskError")
        if not is_ip_addr(gateway):
            return get_error_result("GatewayError")
        if not is_ip_addr(dns1):
            return get_error_result("DnsAddressError")
        netmask_bits = is_netmask(netmask)[1]
        network_num = ipaddress.ip_interface(start_ip + '/' +
                                             str(netmask_bits)).network
        flag_a = ipaddress.ip_network(start_ip).compare_networks(
            ipaddress.ip_network(yzy_group.start_ip))
        flag_b = ipaddress.ip_network(start_ip).compare_networks(
            ipaddress.ip_network(yzy_group.end_ip))
        if flag_a == -1 or flag_b == 1:
            logger.error(
                "terminal repeat modify ip param error: ip not in address segment"
            )
            return get_error_result("IpAddressSegmentError")
        if ipaddress.IPv4Address(gateway) not in network_num:
            logger.error(
                "terminal repeat modify ip param error: ip address and gateway not in same network segment"
            )
            return get_error_result("GatewayAndIpError")
        terminal_count = len(
            self.get_all_object(YzyTerminal, {"group_uuid": group_uuid}))
        if terminal_count == 0:
            logger.error(
                "terminal repeat modify ip param error: no terminal this group"
            )
            return get_error_result("TerminalGroupError")
        group_end_ip = ipaddress.IPv4Address(yzy_group.end_ip)
        ip_resources = [
            x for x in network_num.hosts()
            if ipaddress.IPv4Address(start_ip) <= x <= group_end_ip
        ]
        if len(ip_resources) < terminal_count:
            logger.error(
                "terminal repeat modify ip param error: IpResourcesError")
            return get_error_result("IpResourcesError")
        terminals = self.get_all_object(YzyTerminal, {
            "group_uuid": group_uuid
        }).order_by("terminal_id")
        name_list = list()
        mac_list = list()
        ips = list()
        for terminal in terminals:
            mac = terminal.mac
            name = terminal.name
            if mac not in mac_list:
                mac_list.append(mac)
            if name not in name_list:
                name_list.append(name)
            ips.append(ip_resources[terminal.terminal_id - 1].exploded)

        # start_num = int(start_ip.split(".")[-1])
        # end_num = start_num + max(max_num) - 1
        # if end_num > 254:
        #     logger.error("terminal modify sort ip error")
        #     return get_error_result("TerminalSortIpError")
        # _ip = start_ip.split(".")
        # _ip[-1] = str(end_num)
        # end_ip = ".".join(_ip)
        # ips = find_ips(start_ip, end_ip)
        ips_str = ",".join(ips)
        mac_list_str = ",".join(mac_list)
        req_data = {
            "handler": "WebTerminalHandler",
            "command": "modify_ip",
            "data": {
                "mac_list": mac_list_str,
                "to_ip_list": ips_str,
                "mask": netmask,
                "gateway": gateway,
                "dns1": dns1,
                "dns2": dns2 if is_ip_addr(dns2) else ""
            }
        }
        ret = terminal_post("/api/v1/terminal/task", req_data)
        msg = "终端重排IP: %s" % "/".join(name_list)
        insert_operation_log(msg, ret["msg"])
        if ret.get("code", -1) != 0:
            logger.error("terminal repeat sort ip fail")
            return ret

        logger.info("terminal repeat sort ip success!!! %s" %
                    ("/".join(name_list)))
        return ret