示例#1
0
def perm_sudo_add(request, res, *args):
    """
    list sudo commands alias
    """
    res['operator'] = u"添加别名"
    response = {'success': False, 'error': ''}
    res['emer_content'] = 6
    if request.method == "POST":
        try:
            name = request.POST.get("sudo_name").strip().upper()
            comment = request.POST.get("sudo_comment")
            commands = request.POST.get("sudo_commands").strip()

            if not name or not commands:
                raise ServerError(u"sudo name 和 commands是必填项!")

            pattern = re.compile(r'[\n,\r]')
            deal_space_commands = list_drop_str(pattern.split(commands), u'')
            deal_all_commands = map(trans_all, deal_space_commands)
            commands = ', '.join(deal_all_commands)
            logger.debug(u'添加sudo %s: %s' % (name, commands))

            sudo_name_test = get_object(PermSudo, name=name)
            if sudo_name_test:
                raise ServerError(u"别名[%s]已存在" % name)

            sudo_uuid = str(uuid.uuid1())
            # TODO 保存数据到magicstack
            sudo = PermSudo.objects.create(uuid_id=sudo_uuid,
                                           name=name.strip(),
                                           comment=comment,
                                           commands=commands)

            # TODO 保存数据到proxy上的数据库
            proxy_list = Proxy.objects.all()
            data = {
                'uuid_id': sudo_uuid,
                'id': sudo.id,
                'name': name,
                'comment': comment,
                'commands': commands
            }
            data = json.dumps(data)
            execute_thread_tasks(proxy_list,
                                 THREAD_NUMBERS,
                                 role_proxy_operator,
                                 request.user.username,
                                 'PermSudo',
                                 data,
                                 obj_uuid=sudo.uuid_id,
                                 action='add')
            res['content'] = u"添加Sudo命令别名[%s]成功" % name
            res['emer_status'] = u"添加Sudo命令别名[%s]成功" % name
            response['success'] = True
        except ServerError as e:
            res['flag'] = 'false'
            res['content'] = e.message
            res['emer_status'] = u"添加Sudo命令别名失败:%s" % (e.message)
            response['error'] = res['emer_status']
    return HttpResponse(json.dumps(response), content_type='application/json')
示例#2
0
def media_add(request, res, *args):
    response = {'success': False, 'error': ''}
    res['operator'] = u'添加告警媒介'
    if request.method == 'POST':
        try:
            media_name = request.POST.get('media_name', '')
            if EmergencyType.objects.filter(name=media_name):
                    raise ServerError(u'名称[%s]已存在'%media_name)
            media_type = request.POST.get('media_type', '')
            if media_type == '0':
                smtp_host = request.POST.get('smtp_host', '')
                smtp_host_port = request.POST.get('smtp_host_port', 587)
                email_user = request.POST.get('email_user', '')
                email_user_password = request.POST.get('email_user_password', '')
                encrypt_password = CRYPTOR.encrypt(email_user_password)
                connect_security = request.POST.getlist('connection', [])
                status = request.POST.get('extra', '0')
                comment = request.POST.get('comment', '')
                is_use_tls = True if '1' in connect_security else 0
                is_use_ssl = True if '0' in connect_security else 0
                media_detail = u"SMTP服务器:{0}    SMTP电邮:{1}".format(smtp_host, email_user)

                if '' in [media_name, smtp_host, smtp_host_port, email_user, email_user_password]:
                    raise ServerError(u'必要参数不能为空,请从新填写')

                EmergencyType.objects.create(name=media_name, type=media_type, smtp_server=smtp_host, smtp_server_port=int(smtp_host_port),
                                             status=status, email_username=email_user, email_password=encrypt_password,
                                             email_use_ssl=is_use_ssl, email_use_tls=is_use_tls,detail=media_detail, comment=comment)

                res['content'] = u'添加告警媒介[%s]成功' % media_name
                response['success'] = True
                response['error'] = u'添加告警媒介[%s]成功' % media_name
            elif media_type == '1':
                corpid = request.POST.get('corpid', '')
                corpsecret = request.POST.get('corpsecret', '')
                status = request.POST.get('extra', '0')
                comment = request.POST.get('comment', '')

                if '' in [media_name, corpid, corpsecret]:
                    raise ServerError(u'必要参数为空,请从新填写!')

                media_detail = u'CorpID:%s '%corpid
                EmergencyType.objects.create(name=media_name, type=media_type, corpid=corpid, corpsecret=corpsecret,
                                             detail=media_detail, status=status, comment=comment)
                res['content'] = u'添加成功'
                response['success'] = True
                response['error'] = u'添加成功'
        except Exception as e:
            res['flag'] = False
            res['content'] = e.message
            response['error'] = u'添加media失败:%s'%e.message
    return HttpResponse(json.dumps(response), content_type='application/json')
示例#3
0
def perm_role_detail(request):
    """
    the role detail page
        the role_info data like:
            {'asset_groups': [],
            'assets': [<Asset: 192.168.10.148>],
            'rules': [<PermRule: PermRule object>],
            '': [],
            '': [<User: user1>]}
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户详情"

    try:
        if request.method == "GET":
            role_id = request.GET.get("id")
            if not role_id:
                raise ServerError("not role id")
            role = get_object(PermRole, id=int(role_id))
            role_info = get_role_info(role_id)

            # 系统用户推送记录
            rules = role_info.get("rules")
            assets = role_info.get("assets")
            asset_groups = role_info.get("asset_groups")
            users = role_info.get("users")
            user_groups = role_info.get("user_groups")
            pushed_asset, need_push_asset = get_role_push_host(
                get_object(PermRole, id=role_id))

            # 系统用户在proxy上的操作记录
            role_operator_record = Task.objects.filter(
                role_name=role.name).filter(role_uuid=role.uuid_id)
    except ServerError, e:
        logger.error(e)
示例#4
0
def perm_role_delete(request, res, *args):
    """
    删除系统用户
    """
    res['operator'] = '删除系统用户'
    res['emer_content'] = 6
    if request.method == "GET":
        try:
            # 获取参数删除的role对象
            role_id = request.GET.get("id")
            role = get_object(PermRole, id=int(role_id))
            if not role:
                logger.warning(u"Delete Role: role_id %s not exist" % role_id)
                raise ServerError(u"role_id %s 无数据记录" % role_id)
            filter_type = request.GET.get("filter_type")
            if filter_type:
                if filter_type == "recycle_assets":
                    recycle_assets = [
                        push.asset for push in role.perm_push.all()
                        if push.success
                    ]
                    recycle_assets_ip = ','.join(
                        [asset.name for asset in recycle_assets])
                    return HttpResponse(recycle_assets_ip)
                else:
                    return HttpResponse("no such filter_type: %s" %
                                        filter_type)
            else:
                return HttpResponse("filter_type: ?")
        except ServerError, e:
            return HttpResponse(e)
示例#5
0
def perm_role_recycle(request):
    role_id = request.GET.get('role_id')
    asset_ids = request.GET.get('asset_id').split(',')

    # 仅有推送的角色才回收
    assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids]
    recycle_assets = []
    for asset in assets:
        if True in [push.success for push in asset.perm_push.all()]:
            recycle_assets.append(asset)
    recycle_resource = gen_resource(recycle_assets)
    task = MyTask(recycle_resource)
    try:
        msg_del_user = task.del_user(get_object(PermRole, id=role_id).name)
        msg_del_sudo = task.del_user_sudo(
            get_object(PermRole, id=role_id).name)
        logger.info("recycle user msg: %s" % msg_del_user)
        logger.info("recycle sudo msg: %s" % msg_del_sudo)
    except Exception, e:
        logger.warning("Recycle Role failed: %s" % e)
        raise ServerError(u"回收已推送的系统用户失败: %s" % e)
示例#6
0
def media_edit(request, res):
    res['operator'] = u'编辑告警媒介'
    if request.method == 'GET':
        try:
            media_id = request.GET.get('id', '')
            media_info = EmergencyType.objects.get(id=int(media_id))
            rest = {}
            rest['Id'] = media_info.id
            rest['name'] = media_info.name
            rest['type'] = media_info.type
            rest['status'] = media_info.status
            rest['smtp_server'] = media_info.smtp_server
            rest['smtp_server_port'] = media_info.smtp_server_port
            rest['email_username'] = media_info.email_username
            email_psswd = CRYPTOR.decrypt(media_info.email_password) if media_info.email_password else ''  # 将密码解密后在传到前端
            rest['email_password'] = email_psswd
            rest['email_use_tls'] = media_info.email_use_tls
            rest['email_use_ssl'] = media_info.email_use_ssl
            rest['corpid'] = media_info.corpid
            rest['corpsecret'] = media_info.corpsecret
            rest['comment'] = media_info.comment
            return HttpResponse(json.dumps(rest), content_type='application/json')
        except Exception as e:
            logger.error(e.message)
            return HttpResponse(e.message)
    else:
        response = {'success': False, 'error': ''}
        m_id = request.GET.get('id', '')
        media = EmergencyType.objects.get(id=int(m_id))
        media_name = request.POST.get('media_name', '')
        media_type = request.POST.get('media_type', '')
        try:
            old_name=media.name
            if old_name==media_name:
                if EmergencyType.objects.filter(name=media_name).count()>1:
                    raise ServerError(u'名称[%s]已存在'% media_name)
            else:
                if EmergencyType.objects.filter(name=media_name).count()>0:
                    raise ServerError(u"名称[%s]已存在"% media_name)
            if media_type == '0':
                smtp_host = request.POST.get('smtp_host', '')
                smtp_host_port = int(request.POST.get('smtp_host_port', 587))
                email_user = request.POST.get('email_user', '')
                email_user_password = request.POST.get('email_user_password', '')
                encrypt_password = CRYPTOR.encrypt(email_user_password)
                connect_security = request.POST.getlist('connection', [])
                status = request.POST.get('extra', '0')
                comment = request.POST.get('comment', '')
                is_use_tls = True if '1' in connect_security else 0
                is_use_ssl = True if '0' in connect_security else 0
                media_detail = u"SMTP服务器:{0}    SMTP电邮:{1}".format(smtp_host, email_user)

                if '' in [media_name, smtp_host, smtp_host_port, email_user, email_user_password]:
                    raise ServerError(u'名称不能为空')

                media.name = media_name
                media.type = media_type
                media.smtp_server = smtp_host
                media.smtp_server_port = smtp_host_port
                media.status = status
                media.email_username = email_user
                media.email_password = encrypt_password
                media.email_use_ssl = is_use_ssl
                media.email_use_tls = is_use_tls
                media.detail = media_detail
                media.comment = comment
                media.save()

                res['content'] = u'修改告警媒介[%s]成功' % media_name
                response['success'] = True
            elif media_type == '1':

                corpid = request.POST.get('corpid', '')
                corpsecret = request.POST.get('corpsecret', '')
                status = request.POST.get('extra', '0')
                comment = request.POST.get('comment', '')
                media_detail = u'CorpID:%s'%corpid
                if '' in [media_name, corpid, corpsecret]:
                    raise ServerError(u'必要参数为空,请从新填写!')

                media.name = media_name
                media.type = media_type
                media.status = status
                media.corpid = corpid
                media.detail = media_detail
                media.corpsecret = corpsecret
                media.comment = comment
                media.save()
                res['content'] = u'修改告警媒介[%s]成功'%media.name
                response['success'] = True
        except Exception as e:
            logger.error(e)
            res['flag'] = 'false'
            response['error'] =res['content'] = u'修改告警媒介失败:%s'%e.message
        return HttpResponse(json.dumps(response), content_type='application/json')
示例#7
0
def push_role_to_asset(asset_list, role, username, proxy=None):
    """from permManage.ansible_api import MyTask
    推送系统用户到远程主机上
    """
    try:
        proxy_assets = Asset.objects.filter(proxy__proxy_name=proxy.proxy_name)
        need_push_assets = list(set(asset_list) & set(proxy_assets))
        push_resource = gen_resource(need_push_assets)

        # TODO 调用Ansible API 进行推送
        host_list = [
            asset.networking.all()[0].ip_address for asset in need_push_assets
        ]
        host_names = [asset.name for asset in need_push_assets]
        if host_list:
            task = MyTask(push_resource, host_list)
            ret = {}

            # 因为要先建立用户,而push key是在 password也完成的情况下的可选项
            # 1. 以秘钥 方式推送角色
            role_proxy = get_one_or_all('PermRole', proxy, role.uuid_id)
            ret["pass_push"] = task.add_user(role.name, proxy,
                                             role.system_groups, username)
            time.sleep(1)  # 暂停1秒,保证用户创建完成之后再推送key
            ret["key_push"] = task.push_key(
                role.name, os.path.join(role_proxy['key_path'], 'id_rsa.pub'),
                proxy, username)

            # 2. 推送账号密码 <为了安全 系统用户统一使用秘钥进行通信,不再提供密码方式的推送>
            # 3. 推送sudo配置文件
            sudo_list = [sudo for sudo in role.sudo.all()]
            if sudo_list:
                sudo_uuids = [sudo.uuid_id for sudo in role.sudo.all()]
                ret['sudo'] = task.push_sudo(role, sudo_uuids, proxy, username)
            logger.info('推送用户结果ret:%s' % ret)

            # TODO 将事件放进queue中
            event_task_names = []
            if ret.has_key('pass_push'):
                tk_pass_push = ret['pass_push']['task_name']
                event_task_names.append(tk_pass_push)
            if ret.has_key('key_push'):
                tk_key_push = ret['key_push']['task_name']
                event_task_names.append(tk_key_push)
            if ret.has_key('sudo'):
                if 'task_name' in ret['sudo']:
                    tk_sudo_push = ret['sudo']['task_name']
                    event_task_names.append(tk_sudo_push)
            event = dict(push_assets=host_names,
                         role_name=role.name,
                         password_push=False,
                         key_push=True,
                         task_proxy=proxy.proxy_name)
            event['tasks'] = event_task_names
            event['username'] = username
            task_queue.put(event)

            # TODO 记录task事件
            for item in event['tasks']:
                tk = Task()
                tk.task_name = item
                tk.status = 'running'
                tk.start_time = datetime.datetime.now()
                tk.username = username
                tk.save()
    except Exception as e:
        raise ServerError(e)
示例#8
0
def perm_sudo_edit(request, res, *args):
    """
    编辑别名
    """
    res['operator'] = "编辑别名"
    res['emer_content'] = 6
    if request.method == "GET":
        sudo_id = request.GET.get("id")
        sudo = PermSudo.objects.get(id=sudo_id)
        rest = {}
        rest['Id'] = sudo.id
        rest['name'] = sudo.name
        rest['commands'] = sudo.commands
        rest['comment'] = sudo.comment
        return HttpResponse(json.dumps(rest), content_type='application/json')
    else:
        response = {'success': False, 'error': ''}
        try:
            sudo_id = request.GET.get("id")
            sudo = PermSudo.objects.get(id=int(sudo_id))
            name = request.POST.get("sudo_name").upper()
            commands = request.POST.get("sudo_commands")
            comment = request.POST.get("sudo_comment")

            if not name or not commands:
                raise ServerError(u"sudo name 和 commands是必填项!")

            old_name = sudo.name
            if old_name == name:
                if len(PermSudo.objects.filter(name=name)) > 1:
                    raise ServerError(u'别名[%s]已存在' % name)
            else:
                if len(PermSudo.objects.filter(name=name)) > 0:
                    raise ServerError(u'别名[%s]已存在' % name)

            pattern = re.compile(r'[\n,\r]')
            deal_space_commands = list_drop_str(pattern.split(commands), u'')
            deal_all_commands = map(trans_all, deal_space_commands)
            commands = ', '.join(deal_all_commands).strip()
            sudo.name = name.strip()
            sudo.commands = commands
            sudo.comment = comment
            sudo.save()
            proxy_list = Proxy.objects.all()
            # 更新proxy上的数据
            data = {
                'name': name.strip(),
                'comment': comment,
                'commands': commands
            }
            data = json.dumps(data)
            execute_thread_tasks(proxy_list,
                                 THREAD_NUMBERS,
                                 role_proxy_operator,
                                 request.user.username,
                                 'PermSudo',
                                 data,
                                 obj_uuid=sudo.uuid_id,
                                 action='update')

            msg = u"编辑Sudo命令别名[%s]成功" % sudo.name
            res['content'] = msg
            res['emer_status'] = msg
            response['success'] = True
        except ServerError as e:
            res['flag'] = 'false'
            res['content'] = e.message
            res['emer_status'] = u"编辑Sudo命令别名失败:%s" % (e.message)
            response['error'] = res['emer_status']
        return HttpResponse(json.dumps(response),
                            content_type='application/json')
示例#9
0
def perm_rule_add(request, res, *args):
    """
    add rule page
    添加授权
    """
    response = {'success': False, 'error': ''}
    res['operator'] = "添加授权规则"
    res['emer_content'] = 6
    if request.method == 'POST':
        users_select = request.POST.getlist('user', [])  # 需要授权用户
        user_groups_select = request.POST.getlist('user_group', [])  # 需要授权用户组
        assets_select = request.POST.getlist('asset', [])  # 需要授权资产
        asset_groups_select = request.POST.getlist('asset_group',
                                                   [])  # 需要授权资产组
        roles_select = request.POST.getlist('role', [])  # 需要授权角色
        rule_name = request.POST.get('name')
        rule_comment = request.POST.get('comment')

        try:
            rule = get_object(PermRule, name=rule_name)

            if rule:
                raise ServerError(u'授权规则名称已存在')

            if not rule_name or not roles_select:
                raise ServerError(u'系统用户名称和规则名称不能为空')

            # 获取需要授权的主机列表
            assets_obj = [
                Asset.objects.get(id=asset_id) for asset_id in assets_select
            ]
            asset_groups_obj = [
                AssetGroup.objects.get(id=group_id)
                for group_id in asset_groups_select
            ]
            group_assets_obj = []
            for asset_group in asset_groups_obj:
                group_assets_obj.extend(list(asset_group.asset_set.all()))
            calc_assets = set(group_assets_obj) | set(
                assets_obj)  # 授权资产和资产组包含的资产

            # 获取需要授权的用户列表
            users_obj = [
                User.objects.get(id=user_id) for user_id in users_select
            ]
            user_groups_obj = [
                UserGroup.objects.get(id=group_id)
                for group_id in user_groups_select
            ]

            # 获取授予的角色列表
            roles_obj = [
                PermRole.objects.get(id=role_id) for role_id in roles_select
            ]
            need_push_asset = set()

            for role in roles_obj:
                asset_no_push = get_role_push_host(
                    role=role)[1]  # 获取某角色已经推送的资产
                need_push_asset.update(set(calc_assets) & set(asset_no_push))
                if need_push_asset:
                    raise ServerError(
                        u'没有推送系统用户 %s 的主机 %s' % (role.name, ','.join(
                            [asset.name for asset in need_push_asset])))

            # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色)
            rule = PermRule.objects.create(name=rule_name,
                                           comment=rule_comment)
            rule.user = users_obj
            rule.user_group = user_groups_obj
            rule.asset = assets_obj
            rule.asset_group = asset_groups_obj
            rule.role = roles_obj
            rule.save()

            res['content'] = u"添加授权规则:[%s]" % rule.name
            res['emer_status'] = u"添加授权规则:[%s]成功" % rule.name
            response['success'] = True
        except ServerError, e:
            res['flag'] = 'false'
            res['content'] = e.message
            res['emer_status'] = response[
                'error'] = u"添加授权规则[{0}]失败:{1}".format(rule_name, e.message)
        return HttpResponse(json.dumps(response),
                            content_type='application/json')
示例#10
0
def perm_role_edit(request, res, *args):
    """
    编辑系统用户
    """
    # 渲染数据
    res['operator'] = u"编辑系统用户"
    res['emer_content'] = 6
    if request.method == "GET":
        role_id = request.GET.get("id")
        role = PermRole.objects.get(id=int(role_id))
        if not role:
            return HttpResponse(u'系统用户不存在')
        rest = {}
        rest['Id'] = role.id
        rest['role_name'] = role.name
        rest['role_password'] = role.password
        rest['role_comment'] = role.comment
        rest['system_groups'] = role.system_groups
        rest['sudos'] = ','.join([str(item.id) for item in role.sudo.all()])
        return HttpResponse(json.dumps(rest), content_type='application/json')
    else:
        response = {'success': False, 'error': ''}
        role_id = request.GET.get("id", '')
        role = PermRole.objects.get(id=int(role_id))
        role_name = request.POST.get("role_name")
        role_password = request.POST.get("role_password")
        role_comment = request.POST.get("role_comment")
        role_sudo_names = request.POST.getlist("sudo_name")
        role_sudos = [
            PermSudo.objects.get(id=int(sudo_id))
            for sudo_id in role_sudo_names
        ]
        key_content = request.POST.get("role_key", "")
        sudo_uuids = [item.uuid_id for item in role_sudos]
        sys_groups = request.POST.get("sys_groups", '').strip()
        try:
            if not role:
                raise ServerError('该系统用户不能存在')

            if role_name == "root":
                raise ServerError(u'禁止使用root用户作为系统用户,这样非常危险!')

            if role_password:
                encrypt_pass = CRYPTOR.encrypt(role_password)
                role.password = encrypt_pass

            role_key_content = ""  # key_content为空表示用户秘钥不变,不为空就根据私钥生成公钥
            # TODO 生成随机密码,生成秘钥对
            if key_content:
                try:
                    key_contents = json.dumps(gen_keys(key=key_content))
                    role.key_content = key_contents
                    role_key_content = key_contents
                except SSHException:
                    raise ServerError(u'输入的密钥不合法')
            # 跟新server上的permrole
            role.name = role_name
            role.comment = role_comment
            role.system_groups = sys_groups
            role.sudo = role_sudos
            role.save()

            # 更新proxy上的permrole
            data = {
                'name': role_name,
                'password': role_password,
                'comment': role_comment,
                'sudo_uuids': sudo_uuids,
                'key_content': role_key_content,
                'sys_groups': sys_groups
            }
            data = json.dumps(data)
            proxy_list = Proxy.objects.all()
            execute_thread_tasks(proxy_list,
                                 THREAD_NUMBERS,
                                 role_proxy_operator,
                                 request.user.username,
                                 'PermRole',
                                 data,
                                 obj_uuid=role.uuid_id,
                                 action='update')
            # TODO 用户操作记录
            res['content'] = u"编辑系统用户[%s]成功" % role.name
            # TODO 告警事件记录
            res['emer_status'] = u"编辑系统用户[%s]成功" % role.name
            # TODO 页面返回信息
            response['success'] = True
        except ServerError, e:
            res['flag'] = 'false'
            res['content'] = e.message
            res['emer_status'] = u"编辑系统用户失败:%s" % (e.message)
            response['error'] = u"编辑系统用户失败:%s" % (e.message)
        return HttpResponse(json.dumps(response),
                            content_type='application/json')
示例#11
0
def perm_role_add(request, res, *args):
    """
    添加系统用户 server和proxy上都添加
    """
    response = {'success': False, 'error': ''}
    res['operator'] = u"添加系统用户"
    res['emer_content'] = 6
    if request.method == "POST":
        name = request.POST.get("role_name", "").strip()
        comment = request.POST.get("role_comment", "")
        password = request.POST.get("role_password", "")
        key_content = request.POST.get("role_key", "")
        sudo_ids = request.POST.getlist('sudo_name')
        uuid_id = str(uuid.uuid1())
        sys_groups = request.POST.get('sys_groups', '').strip()

        try:
            if get_object(PermRole, name=name):
                raise ServerError(u'用户 %s已经存在' % name)
            if name == "root":
                raise ServerError(u'禁止使用root用户作为系统用户,这样非常危险!')
            if name == "":
                raise ServerError(u'系统用户名为空')

            if password:
                encrypt_pass = CRYPTOR.encrypt(password)
            else:
                encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20))
            # 生成随机密码,生成秘钥对
            sudos_obj = [
                get_object(PermSudo, id=int(sudo_id)) for sudo_id in sudo_ids
            ]
            sudo_uuids = [item.uuid_id for item in sudos_obj]
            try:
                keys_content = json.dumps(gen_keys(key_content))
            except Exception, e:
                raise ServerError(e)

            #  # TODO 将数据保存到magicstack上
            role = PermRole.objects.create(uuid_id=uuid_id,
                                           name=name,
                                           comment=comment,
                                           password=encrypt_pass,
                                           key_content=keys_content,
                                           system_groups=sys_groups)
            role.sudo = sudos_obj
            role.save()

            # TODO 将数据同时保存到proxy上
            proxy_list = Proxy.objects.all()
            data = {
                'uuid_id': uuid_id,
                'id': role.id,
                'name': name,
                'password': encrypt_pass,
                'comment': comment,
                'key_content': keys_content,
                'sudo_uuids': sudo_uuids,
                'sys_groups': sys_groups
            }
            data = json.dumps(data)
            execute_thread_tasks(proxy_list,
                                 THREAD_NUMBERS,
                                 role_proxy_operator,
                                 request.user.username,
                                 'PermRole',
                                 data,
                                 obj_uuid=role.uuid_id,
                                 action='add')
            response['success'] = True
            res['content'] = u'添加系统用户[%s]成功' % role.name
            res['emer_status'] = u'添加系统用户[%s]成功' % role.name
        except ServerError, e:
            res['flag'] = 'false'
            res['content'] = e.message
            res['emer_status'] = u"添加系统用户失败:%s" (e.message)
            response['error'] = u"添加系统用户失败:%s" % (e.message)
示例#12
0
def perm_rule_edit(request, res, *args):
    """
    edit rule page
    """
    res['operator'] = "编辑授权规则"
    res['emer_content'] = 6
    if request.method == 'GET':
        try:
            rule_id = request.GET.get("id")
            rule = get_object(PermRule, id=int(rule_id))
            if rule:
                rest = {}
                rest['Id'] = rule.id
                rest['name'] = rule.name
                rest['comment'] = rule.comment
                rest['asset'] = ','.join(
                    [str(item.id) for item in rule.asset.all()])
                rest['asset_group'] = ','.join(
                    str(item.id) for item in rule.asset_group.all())
                rest['user'] = '******'.join(
                    str(item.id) for item in rule.user.all())
                rest['user_group'] = ','.join(
                    str(item.id) for item in rule.user_group.all())
                rest['role'] = ','.join(
                    str(item.id) for item in rule.role.all())
                return HttpResponse(json.dumps(rest),
                                    content_type='application/json')
            else:
                return HttpResponse(u'授权规则不存在')
        except Exception as e:
            logger.error(e)
    else:
        response = {'success': False, 'error': ''}
        rule_id = request.GET.get("id")
        rule = get_object(PermRule, id=int(rule_id))
        rule_name_old = rule.name
        rule_name = request.POST.get('name')
        rule_comment = request.POST.get("comment")
        users_select = request.POST.getlist('user', [])
        user_groups_select = request.POST.getlist('user_group', [])
        assets_select = request.POST.getlist('asset', [])
        asset_groups_select = request.POST.getlist('asset_group', [])
        roles_select = request.POST.getlist('role', [])

        try:
            if not rule_name or not roles_select:
                raise ServerError(u'系统用户和关联系统用户不能为空')
            if rule_name_old == rule_name:
                if len(PermRule.objects.filter(name=rule_name)) > 1:
                    raise ServerError(u'授权规则名称[%s]已存在' % rule_name)
            else:
                if len(PermRule.objects.filter(name=rule_name)) > 0:
                    raise ServerError(u'授权规则名称[%s]已存在' % rule_name)

            assets_obj = [
                Asset.objects.get(id=asset_id) for asset_id in assets_select
            ]
            asset_groups_obj = [
                AssetGroup.objects.get(id=group_id)
                for group_id in asset_groups_select
            ]
            group_assets_obj = []
            for asset_group in asset_groups_obj:
                group_assets_obj.extend(list(asset_group.asset_set.all()))
            calc_assets = set(group_assets_obj) | set(
                assets_obj)  # 授权资产和资产组包含的资产

            # 获取需要授权的用户列表
            users_obj = [
                User.objects.get(id=user_id) for user_id in users_select
            ]
            user_groups_obj = [
                UserGroup.objects.get(id=group_id)
                for group_id in user_groups_select
            ]

            # 获取授予的角色列表
            roles_obj = [
                PermRole.objects.get(id=role_id) for role_id in roles_select
            ]
            need_push_asset = set()
            for role in roles_obj:
                asset_no_push = get_role_push_host(
                    role=role)[1]  # 获取某角色已经推送的资产
                need_push_asset.update(set(calc_assets) & set(asset_no_push))
                if need_push_asset:
                    raise ServerError(
                        u'没有推送系统用户 %s 的主机 %s' % (role.name, ','.join(
                            [asset.name for asset in need_push_asset])))

                # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色)
                rule.user = users_obj
                rule.user_group = user_groups_obj
                rule.asset = assets_obj
                rule.asset_group = asset_groups_obj
                rule.role = roles_obj
            rule.name = rule_name
            rule.comment = rule_comment
            rule.save()
            res['content'] = u"编辑授权规则[%s]成功" % rule_name_old
            res['emer_status'] = u"编辑授权规则[%s]成功" % rule_name_old
            response['success'] = True
        except Exception, e:
            res['flag'] = 'false'
            res['content'] = e.message
            res['emer_status'] = response['error'] = u"编辑授权规则失败:%s" % e.message
        return HttpResponse(json.dumps(response),
                            content_type='application/json')
示例#13
0
                     [asset.name for asset in recycle_assets])
                 return HttpResponse(recycle_assets_ip)
             else:
                 return HttpResponse("no such filter_type: %s" %
                                     filter_type)
         else:
             return HttpResponse("filter_type: ?")
     except ServerError, e:
         return HttpResponse(e)
 if request.method == "POST":
     try:
         role_id = request.POST.get("id")
         role = get_object(PermRole, id=int(role_id))
         if not role:
             logger.warning(u"Delete Role: role_id %s not exist" % role_id)
             raise ServerError(u"role_id %s 无数据记录" % role_id)
         recycle_assets = [
             push.asset for push in role.perm_push.all() if push.success
         ]
         logger.debug(u"delete role %s - delete_assets: %s" %
                      (role.name, recycle_assets))
         if recycle_assets:
             asset_proxys = gen_asset_proxy(recycle_assets)
             for key, value in asset_proxys.items():
                 proxy = Proxy.objects.filter(proxy_name=key)[0]
                 recycle_resource = gen_resource(value)
                 host_list = [
                     asset.networking.all()[0].ip_address for asset in value
                 ]
                 task = MyTask(recycle_resource, host_list)
                 try: