示例#1
0
def perm_role_edit(request):
    """
    edit role page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户编辑"

    # 渲染数据
    role_id = request.GET.get("id")
    role = PermRole.objects.get(id=role_id)
    role_pass = CRYPTOR.decrypt(role.password)
    sudo_all = PermSudo.objects.all()
    role_sudos = role.sudo.all()
    sudo_all = PermSudo.objects.all()
    if request.method == "GET":
        return my_render('jperm/perm_role_edit.html', locals(), request)

    if request.method == "POST":
        # 获取 POST 数据
        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=sudo_id) for sudo_id in role_sudo_names
        ]
        key_content = request.POST.get("role_key", "")
        if len(role_password) > 64:
            raise ServerError('密码长度不能超过64位!')

        try:
            if not role:
                raise ServerError('该系统用户不能存在')

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

            if role_password:
                encrypt_pass = CRYPTOR.encrypt(role_password)
                role.password = encrypt_pass
            # 生成随机密码,生成秘钥对
            if key_content:
                try:
                    key_path = gen_keys(key=key_content,
                                        key_path_dir=role.key_path)
                except SSHException:
                    raise ServerError('输入的密钥不合法')
                logger.debug('Recreate role key: %s' % role.key_path)
            # 写入数据库
            role.name = role_name
            role.comment = role_comment
            role.sudo = role_sudos

            role.save()
            msg = "更新系统用户: %s" % role.name
            return HttpResponseRedirect(reverse('role_list'))
        except ServerError as e:
            error = e

    return my_render('jperm/perm_role_edit.html', locals(), request)
示例#2
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=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))

    except ServerError as e:
        logger.warning(e)

    return my_render('jperm/perm_role_detail.html', locals(), request)
示例#3
0
def perm_rule_detail(request):
    """
    rule detail page
    授权详情
    """
    # 渲染数据
    header_title, path1, path2 = "授权规则", "规则管理", "规则详情"

    # 根据rule_id 取得rule对象
    try:
        if request.method == "GET":
            rule_id = request.GET.get("id")
            if not rule_id:
                raise ServerError("Rule Detail - no rule id get")
            rule_obj = PermRule.objects.get(id=rule_id)
            user_obj = rule_obj.user.all()
            user_group_obj = rule_obj.user_group.all()
            asset_obj = rule_obj.asset.all()
            asset_group_obj = rule_obj.asset_group.all()
            roles_name = [role.name for role in rule_obj.role.all()]

            # 渲染数据
            roles_name = ','.join(roles_name)
            rule = rule_obj
            users = user_obj
            user_groups = user_group_obj
            assets = asset_obj
            asset_groups = asset_group_obj
    except ServerError as e:
        logger.warning(e)

    return my_render('jperm/perm_rule_detail.html', locals(), request)
示例#4
0
def perm_sudo_edit(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "编辑别名"

    sudo_id = request.GET.get("id")
    sudo = PermSudo.objects.get(id=sudo_id)

    if request.method == "POST":
        name = request.POST.get("sudo_name").upper()
        commands = request.POST.get("sudo_commands")
        comment = request.POST.get("sudo_comment")

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

        sudo.name = name.strip()
        sudo.commands = commands
        sudo.comment = comment
        sudo.save()

        msg = u"更新命令别名: %s" % name

    return my_render('jperm/perm_sudo_edit.html', locals(), request)
示例#5
0
def perm_sudo_add(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "添加别名"

    if request.method == "POST":
        # 获取参数: name, comment
        name = request.POST.get("sudo_name").strip().upper()
        comment = request.POST.get("sudo_comment").strip()
        commands = request.POST.get("sudo_commands").strip()

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

        if get_object(PermSudo, name=name):
            error = 'Sudo别名 %s已经存在' % name
        else:
            sudo = PermSudo(name=name.strip(),
                            comment=comment,
                            commands=commands)
            sudo.save()
            msg = u"添加Sudo命令别名: %s" % name
        # 渲染数据

    return my_render('jperm/perm_sudo_add.html', locals(), request)
示例#6
0
def group_add(request):
    """
    group add view for route
    添加用户组的视图
    """
    error = ''
    msg = ''
    header_title, path1, path2 = '添加用户组', '用户管理', '添加用户组'
    user_all = User.objects.all()

    if request.method == 'POST':
        group_name = request.POST.get('group_name', '')
        users_selected = request.POST.getlist('users_selected', '')
        comment = request.POST.get('comment', '')

        try:
            if not group_name:
                error = '组名 不能为空'
                raise ServerError(error)

            if UserGroup.objects.filter(name=group_name):
                error = '组名已存在'
                raise ServerError(error)
            db_add_group(name=group_name,
                         users_id=users_selected,
                         comment=comment)
        except ServerError:
            pass
        except TypeError:
            error = '添加小组失败'
        else:
            msg = '添加组 %s 成功' % group_name

    return my_render('juser/group_add.html', locals(), request)
示例#7
0
def perm_sudo_add(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "添加别名"

    if request.method == "POST":
        # 获取参数: name, comment
        name = request.POST.get("sudo_name").strip().upper()
        comment = request.POST.get("sudo_comment").strip()
        commands = request.POST.get("sudo_commands").strip()

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

        if get_object(PermSudo, name=name):
            error = 'Sudo别名 %s已经存在' % name
        else:
            sudo = PermSudo(name=name.strip(), comment=comment, commands=commands)
            sudo.save()
            msg = u"添加Sudo命令别名: %s" % name
        # 渲染数据

    return my_render('jperm/perm_sudo_add.html', locals(), request)
示例#8
0
def change_info(request):
    header_title, path1, path2 = '修改信息', '用户管理', '修改个人信息'
    user_id = request.user.id
    user = User.objects.get(id=user_id)
    error = ''
    if not user:
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        name = request.POST.get('name', '')
        password = request.POST.get('password', '')
        email = request.POST.get('email', '')

        if '' in [name, email]:
            error = '不能为空'

        if not error:
            user.name = name
            user.email = email
            user.save()
            if len(password) > 0:
                user.set_password(password)
                user.save()
            msg = '修改成功'

    return my_render('juser/change_info.html', locals(), request)
示例#9
0
def user_edit(request):
    header_title, path1, path2 = '编辑用户', '用户管理', '编辑用户'
    if request.method == 'GET':
        user_id = request.GET.get('id', '')
        if not user_id:
            return HttpResponseRedirect(reverse('index'))

        user_role = {'SU': '超级管理员', 'CU': '普通用户'}
        user = get_object(User, id=user_id)
        group_all = UserGroup.objects.all()
        if user:
            groups_str = ' '.join(
                [str(group.id) for group in user.group.all()])
            admin_groups_str = ' '.join([
                str(admin_group.group.id)
                for admin_group in user.admingroup_set.all()
            ])

    else:
        user_id = request.GET.get('id', '')
        password = request.POST.get('password', '')
        name = request.POST.get('name', '')
        email = request.POST.get('email', '')
        groups = request.POST.getlist('groups', [])
        role_post = request.POST.get('role', 'CU')
        admin_groups = request.POST.getlist('admin_groups', [])
        extra = request.POST.getlist('extra', [])
        is_active = True if '0' in extra else False
        email_need = True if '1' in extra else False
        user_role = {'SU': '超级管理员', 'GA': '部门管理员', 'CU': '普通用户'}

        if user_id:
            user = get_object(User, id=user_id)
        else:
            return HttpResponseRedirect(reverse('user_list'))

        db_update_user(user_id=user_id,
                       password=password,
                       name=name,
                       email=email,
                       groups=groups,
                       admin_groups=admin_groups,
                       role=role_post,
                       is_active=is_active)

        if email_need:
            msg = """
            Hi %s:
                您的信息已修改,请登录跳板机查看详细信息
                地址:%s
                用户名: %s
                密码:%s (如果密码为None代表密码为原密码)
                权限::%s

            """ % (user.name, settings.URL, user.username, password,
                   user_role.get(role_post, ''))
            send_mail('您的信息已修改', msg, MAIL_FROM, [email], fail_silently=False)

        return HttpResponseRedirect(reverse('user_list'))
    return my_render('juser/user_edit.html', locals(), request)
示例#10
0
def perm_role_list(request):
    """
    list role page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "查看系统用户"
    username = request.user.username
    user_perm = request.session['role_id']
    if user_perm == 2:  # 获取所有系统角色
        roles_list = PermRole.objects.all()
    elif user_perm == 1:
        login_user = get_object(User, username=username)
        roles_list = PermRole.objects.all().filter(
            productLine=login_user.productLine)

    role_id = request.GET.get('id')
    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if keyword:
        roles_list = roles_list.filter(Q(name=keyword))

    if role_id:
        roles_list = roles_list.filter(id=role_id)

    roles_list, p, roles, page_range, current_page, show_first, show_end = pages(
        roles_list, request)

    return my_render('jperm/perm_role_list.html', locals(), request)
示例#11
0
def perm_sudo_list(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "查看别名"

    # 获取所有sudo 命令别名
    username = request.user.username
    user_perm = request.session['role_id']
    if user_perm == 2:
        sudos_list = PermSudo.objects.all()
    elif user_perm == 1:
        login_user = get_object(User, username=username)
        sudos_list = PermSudo.objects.all().filter(
            productLine=login_user.productLine)

    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if keyword:
        sudos_list = sudos_list.filter(Q(name=keyword))

    sudos_list, p, sudos, page_range, current_page, show_first, show_end = pages(
        sudos_list, request)

    return my_render('jperm/perm_sudo_list.html', locals(), request)
示例#12
0
def group_add(request):
    """
    Group add view
    添加资产组
    """
    header_title, path1, path2 = '添加资产组', '资产管理', '添加资产组'
    asset_all = Asset.objects.all()

    if request.method == 'POST':
        name = request.POST.get('name', '')
        asset_select = request.POST.getlist('asset_select', [])
        comment = request.POST.get('comment', '')

        try:
            if not name:
                emg = '组名不能为空'
                raise ServerError(emg)

            asset_group_test = get_object(AssetGroup, name=name)
            if asset_group_test:
                emg = "该组名 %s 已存在" % name
                raise ServerError(emg)

        except ServerError:
            pass

        else:
            db_add_group(name=name, comment=comment, asset_select=asset_select)
            smg = "主机组 %s 添加成功" % name

    return my_render('jasset/group_add.html', locals(), request)
示例#13
0
def perm_sudo_add(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "添加别名"
    try:
        if request.method == "POST":
            # 获取参数: name, comment
            name = request.POST.get("sudo_name").strip().upper()
            comment = request.POST.get("sudo_comment").strip()
            commands = request.POST.get("sudo_commands").strip()

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

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

            if get_object(PermSudo, name=name):
                error = 'Sudo别名 %s已经存在' % name
            else:
                sudo = PermSudo(name=name.strip(),
                                comment=comment,
                                commands=commands)
                sudo.save()
                msg = "添加Sudo命令别名: %s" % name
    except ServerError as e:
        error = e
    return my_render('jperm/perm_sudo_add.html', locals(), request)
示例#14
0
def perm_sudo_edit(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "编辑别名"

    sudo_id = request.GET.get("id")
    sudo = PermSudo.objects.get(id=sudo_id)

    if request.method == "POST":
        name = request.POST.get("sudo_name").upper()
        commands = request.POST.get("sudo_commands")
        comment = request.POST.get("sudo_comment")

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

        sudo.name = name.strip()
        sudo.commands = commands
        sudo.comment = comment
        sudo.save()

        msg = u"更新命令别名: %s" % name

    return my_render('jperm/perm_sudo_edit.html', locals(), request)
示例#15
0
def list_registered_user(request):
    u"""
    列出所有等待处理的注册用户及主机申请记录信息
    
    """
    registered_users = RegisterUser.objects.filter(is_added=0)
    applyhosts = ApplyHosts.objects.filter(is_added=0) 
    return my_render('avazu/list_registered_user.html', locals(), request)
示例#16
0
def log_detail(request, offset):
    log_id = request.GET.get('id')
    if offset == 'exec':
        log = get_object(ExecLog, id=log_id)
        assets_hostname = log.host.split(' ')
        try:
            result = eval(str(log.result))
        except (SyntaxError, NameError):
            result = {}
        return my_render('jlog/exec_detail.html', locals(), request)
    elif offset == 'file':
        log = get_object(FileLog, id=log_id)
        assets_hostname = log.host.split(' ')
        file_list = log.filename.split(' ')
        try:
            result = eval(str(log.result))
        except (SyntaxError, NameError):
            result = {}
        return my_render('jlog/file_detail.html', locals(), request)
示例#17
0
def perm_role_edit(request):
    """
    edit role page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户编辑"

    # 渲染数据
    role_id = request.GET.get("id")
    role = PermRole.objects.get(id=role_id)
    role_pass = CRYPTOR.decrypt(role.password)
    sudo_all = PermSudo.objects.all()
    role_sudos = role.sudo.all()
    sudo_all = PermSudo.objects.all()
    if request.method == "GET":
        return my_render('jperm/perm_role_edit.html', locals(), request)

    if request.method == "POST":
        # 获取 POST 数据
        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=sudo_id) for sudo_id in role_sudo_names]
        key_content = request.POST.get("role_key", "")
        if len(role_password) > 64:
            raise ServerError(u'密码长度不能超过64位!')

        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
            # 生成随机密码,生成秘钥对
            if key_content:
                try:
                    key_path = gen_keys(key=key_content, key_path_dir=role.key_path)
                except SSHException:
                    raise ServerError('输入的密钥不合法')
                logger.debug('Recreate role key: %s' % role.key_path)
            # 写入数据库
            role.name = role_name
            role.comment = role_comment
            role.sudo = role_sudos

            role.save()
            msg = u"更新系统用户: %s" % role.name
            return HttpResponseRedirect(reverse('role_list'))
        except ServerError, e:
            error = e
示例#18
0
def idc_add(request):
    """
    IDC add view
    """
    header_title, path1, path2 = '添加IDC', '资产管理', '添加IDC'
    if request.method == 'POST':
        idc_form = IdcForm(request.POST)
        if idc_form.is_valid():
            idc_name = idc_form.cleaned_data['name']

            if IDC.objects.filter(name=idc_name):
                emg = '添加失败, 此IDC %s 已存在!' % idc_name
                return my_render('jasset/idc_add.html', locals(), request)
            else:
                idc_form.save()
                smg = 'IDC: %s添加成功' % idc_name
            return HttpResponseRedirect(reverse('idc_list'))
    else:
        idc_form = IdcForm()
    return my_render('jasset/idc_add.html', locals(), request)
示例#19
0
def asset_upload(request):
    """
    Upload asset excel file view
    """
    if request.method == 'POST':
        excel_file = request.FILES.get('file_name', '')
        ret = excel_to_db(excel_file)
        if ret:
            smg = '批量添加成功'
        else:
            emg = '批量添加失败,请检查格式.'
    return my_render('jasset/asset_add_batch.html', locals(), request)
示例#20
0
def perm_role_add(request):
    """
    add role page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "添加系统用户"
    sudos = PermSudo.objects.all()

    if request.method == "POST":
        # 获取参数: name, comment
        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')

        try:
            if get_object(PermRole, name=name):
                raise ServerError('已经存在该用户 %s' % name)
            if name == "root":
                raise ServerError('禁止使用root用户作为系统用户,这样非常危险!')
            default = get_object(Setting, name='default')
            if len(password) > 64:
                raise ServerError('密码长度不能超过64位!')

            if password:
                encrypt_pass = CRYPTOR.encrypt(password)
            else:
                encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20))
            # 生成随机密码,生成秘钥对
            sudos_obj = [
                get_object(PermSudo, id=sudo_id) for sudo_id in sudo_ids
            ]
            if key_content:
                try:
                    key_path = gen_keys(key=key_content)
                except SSHException as e:
                    raise ServerError(e)
            else:
                key_path = gen_keys()
            logger.debug('generate role key: %s' % key_path)
            role = PermRole(name=name,
                            comment=comment,
                            password=encrypt_pass,
                            key_path=key_path)
            role.save()
            role.sudo = sudos_obj
            msg = "添加系统用户: %s" % name
            return HttpResponseRedirect(reverse('role_list'))
        except ServerError as e:
            error = e
    return my_render('jperm/perm_role_add.html', locals(), request)
示例#21
0
def idc_edit(request):
    """
    IDC edit view
    """
    header_title, path1, path2 = '编辑IDC', '资产管理', '编辑IDC'
    idc_id = request.GET.get('id', '')
    idc = get_object(IDC, id=idc_id)
    if request.method == 'POST':
        idc_form = IdcForm(request.POST, instance=idc)
        if idc_form.is_valid():
            idc_form.save()
            return HttpResponseRedirect(reverse('idc_list'))
    else:
        idc_form = IdcForm(instance=idc)
        return my_render('jasset/idc_edit.html', locals(), request)
示例#22
0
def idc_list(request):
    """
    IDC list view
    """
    header_title, path1, path2 = '查看IDC', '资产管理', '查看IDC'
    posts = IDC.objects.all()
    keyword = request.GET.get('keyword', '')
    if keyword:
        posts = IDC.objects.filter(
            Q(name__contains=keyword) | Q(comment__contains=keyword))
    else:
        posts = IDC.objects.exclude(name='ALL').order_by('id')
    contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(
        posts, request)
    return my_render('jasset/idc_list.html', locals(), request)
示例#23
0
def upload(request):
    user = request.user
    assets = list(get_group_user_perm(user).get('asset').keys())
    asset_select = []
    if request.method == 'POST':
        remote_ip = request.META.get('REMOTE_ADDR')
        asset_ids = request.POST.getlist('asset_ids', '')
        upload_files = request.FILES.getlist('file[]', None)
        date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        upload_dir = get_tmp_dir()
        # file_dict = {}
        for asset_id in asset_ids:
            asset_select.append(get_object(Asset, id=asset_id))

        if not set(asset_select).issubset(set(assets)):
            illegal_asset = set(asset_select).issubset(set(assets))
            return HttpResponse(
                '没有权限的服务器 %s' %
                ','.join([asset.hostname for asset in illegal_asset]))

        for upload_file in upload_files:
            file_path = '%s/%s' % (upload_dir, upload_file.name)
            with open(file_path, 'wb+') as f:
                for chunk in upload_file.chunks():
                    f.write(chunk)

        res = gen_resource({'user': user, 'asset': asset_select})
        runner = MyRunner(res)
        runner.run('copy',
                   module_args='src=%s dest=%s' % (upload_dir, '/tmp'),
                   pattern='*')
        ret = runner.results
        logger.debug(ret)
        FileLog(user=request.user.username,
                host=' '.join([asset.hostname for asset in asset_select]),
                filename=' '.join([f.name for f in upload_files]),
                type='upload',
                remote_ip=remote_ip,
                result=ret).save()
        if ret.get('failed'):
            error = '上传目录: %s <br> 上传失败: [ %s ] <br>上传成功 [ %s ]' % (
                upload_dir, ', '.join(list(ret.get('failed').keys())),
                ', '.join(list(ret.get('ok').keys())))
            return HttpResponse(error, status=500)
        msg = '上传目录: %s <br> 传送成功 [ %s ]' % (upload_dir, ', '.join(
            list(ret.get('ok').keys())))
        return HttpResponse(msg)
    return my_render('upload.html', locals(), request)
示例#24
0
def group_edit(request):
    error = ''
    msg = ''
    header_title, path1, path2 = '编辑用户组', '用户管理', '编辑用户组'

    if request.method == 'GET':
        group_id = request.GET.get('id', '')
        user_group = get_object(UserGroup, id=group_id)
        # user_group = UserGroup.objects.get(id=group_id)
        users_selected = User.objects.filter(group=user_group)
        users_remain = User.objects.filter(~Q(group=user_group))
        users_all = User.objects.all()

    elif request.method == 'POST':
        group_id = request.POST.get('group_id', '')
        group_name = request.POST.get('group_name', '')
        comment = request.POST.get('comment', '')
        users_selected = request.POST.getlist('users_selected')

        try:
            if '' in [group_id, group_name]:
                raise ServerError('组名不能为空')

            if len(UserGroup.objects.filter(name=group_name)) > 1:
                raise ServerError('%s 用户组已存在' % group_name)
            # add user group
            user_group = get_object_or_404(UserGroup, id=group_id)
            user_group.user_set.clear()

            for user in User.objects.filter(id__in=users_selected):
                user.group.add(UserGroup.objects.get(id=group_id))

            user_group.name = group_name
            user_group.comment = comment
            user_group.save()
        except ServerError as e:
            error = e

        if not error:
            return HttpResponseRedirect(reverse('user_group_list'))
        else:
            users_all = User.objects.all()
            users_selected = User.objects.filter(group=user_group)
            users_remain = User.objects.filter(~Q(group=user_group))

    return my_render('juser/group_edit.html', locals(), request)
示例#25
0
def group_list(request):
    """
    list asset group
    列出资产组
    """
    header_title, path1, path2 = '查看资产组', '资产管理', '查看资产组'
    keyword = request.GET.get('keyword', '')
    asset_group_list = AssetGroup.objects.all()
    group_id = request.GET.get('id')
    if group_id:
        asset_group_list = asset_group_list.filter(id=group_id)
    if keyword:
        asset_group_list = asset_group_list.filter(
            Q(name__contains=keyword) | Q(comment__contains=keyword))

    asset_group_list, p, asset_groups, page_range, current_page, show_first, show_end = pages(
        asset_group_list, request)
    return my_render('jasset/group_list.html', locals(), request)
示例#26
0
def user_detail(request):
    header_title, path1, path2 = '用户详情', '用户管理', '用户详情'
    if request.session.get('role_id') == 0:
        user_id = request.user.id
    else:
        user_id = request.GET.get('id', '')

    user = get_object(User, id=user_id)
    if not user:
        return HttpResponseRedirect(reverse('user_list'))

    user_perm_info = get_group_user_perm(user)
    role_assets = user_perm_info.get('role')
    user_log_ten = Log.objects.filter(user=user.username).order_by('id')[0:10]
    user_log_last = Log.objects.filter(user=user.username).order_by('id')[0:50]
    user_log_last_num = len(user_log_last)

    return my_render('juser/user_detail.html', locals(), request)
示例#27
0
def asset_add(request):
    """
    Asset add view
    添加资产
    """
    header_title, path1, path2 = '添加资产', '资产管理', '添加资产'
    asset_group_all = AssetGroup.objects.all()
    af = AssetForm()
    default_setting = get_object(Setting, name='default')
    default_port = default_setting.field2 if default_setting else ''
    if request.method == 'POST':
        af_post = AssetForm(request.POST)
        ip = request.POST.get('ip', '')
        hostname = request.POST.get('hostname', '')

        is_active = True if request.POST.get('is_active') == '1' else False
        use_default_auth = request.POST.get('use_default_auth', '')
        try:
            if Asset.objects.filter(hostname=str(hostname)):
                error = '该主机名 %s 已存在!' % hostname
                raise ServerError(error)
            if len(hostname) > 54:
                error = "主机名长度不能超过53位!"
                raise ServerError(error)
        except ServerError:
            pass
        else:
            if af_post.is_valid():
                asset_save = af_post.save(commit=False)
                if not use_default_auth:
                    password = request.POST.get('password', '')
                    password_encode = CRYPTOR.encrypt(password)
                    asset_save.password = password_encode
                if not ip:
                    asset_save.ip = hostname
                asset_save.is_active = True if is_active else False
                asset_save.save()
                af_post.save_m2m()

                msg = '主机 %s 添加成功' % hostname
            else:
                esg = '主机 %s 添加失败' % hostname

    return my_render('jasset/asset_add.html', locals(), request)
示例#28
0
def group_edit(request):
    """
    Group edit view
    编辑资产组
    """
    header_title, path1, path2 = '编辑主机组', '资产管理', '编辑主机组'
    group_id = request.GET.get('id', '')
    group = get_object(AssetGroup, id=group_id)

    asset_all = Asset.objects.all()
    asset_select = Asset.objects.filter(group=group)
    asset_no_select = [a for a in asset_all if a not in asset_select]

    if request.method == 'POST':
        name = request.POST.get('name', '')
        asset_select = request.POST.getlist('asset_select', [])
        comment = request.POST.get('comment', '')

        try:
            if not name:
                emg = '组名不能为空'
                raise ServerError(emg)

            if group.name != name:
                asset_group_test = get_object(AssetGroup, name=name)
                if asset_group_test:
                    emg = "该组名 %s 已存在" % name
                    raise ServerError(emg)

        except ServerError:
            pass

        else:
            group.asset_set.clear()
            db_update_group(id=group_id,
                            name=name,
                            comment=comment,
                            asset_select=asset_select)
            smg = "主机组 %s 添加成功" % name

        return HttpResponseRedirect(reverse('asset_group_list'))

    return my_render('jasset/group_edit.html', locals(), request)
示例#29
0
文件: views.py 项目: xiaochao/bounce
def perm_role_add(request):
    """
    add role page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "添加系统用户"
    sudos = PermSudo.objects.all()

    if request.method == "POST":
        # 获取参数: name, comment
        name = request.POST.get("role_name", "")
        if name == 'root':
            error = u'不允许添加root用户为系统用户'
            return my_render('jperm/perm_role_add.html', locals(), request)
        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')

        try:
            if get_object(PermRole, name=name):
                raise ServerError(u'已经存在该用户 %s' % name)
            default = get_object(Setting, name='default')

            if password:
                encrypt_pass = CRYPTOR.encrypt(password)
            else:
                encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20))
            # 生成随机密码,生成秘钥对
            sudos_obj = [get_object(PermSudo, id=sudo_id) for sudo_id in sudo_ids]
            if key_content:
                try:
                    key_path = gen_keys(key=key_content)
                except SSHException, e:
                    raise ServerError(e)
            else:
                key_path = gen_keys()
            logger.debug('generate role key: %s' % key_path)
            role = PermRole(name=name, comment=comment, password=encrypt_pass, key_path=key_path)
            role.save()
            role.sudo = sudos_obj
            msg = u"添加系统用户: %s" % name
            return HttpResponseRedirect(reverse('role_list'))
示例#30
0
def group_list(request):
    """
    list user group
    用户组列表
    """
    header_title, path1, path2 = '查看用户组', '用户管理', '查看用户组'
    keyword = request.GET.get('search', '')
    user_group_list = UserGroup.objects.all().order_by('name')
    group_id = request.GET.get('id', '')

    if keyword:
        user_group_list = user_group_list.filter(
            Q(name__icontains=keyword) | Q(comment__icontains=keyword))

    if group_id:
        user_group_list = user_group_list.filter(id=int(group_id))

    user_group_list, p, user_groups, page_range, current_page, show_first, show_end = pages(
        user_group_list, request)
    return my_render('juser/group_list.html', locals(), request)
示例#31
0
def perm_sudo_list(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "查看别名"

    # 获取所有sudo 命令别名
    sudos_list = PermSudo.objects.all()

    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if keyword:
        sudos_list = sudos_list.filter(Q(name=keyword))

    sudos_list, p, sudos, page_range, current_page, show_first, show_end = pages(sudos_list, request)

    return my_render('jperm/perm_sudo_list.html', locals(), request)
示例#32
0
def perm_sudo_list(request):
    """
    list sudo commands alias
    :param request:
    :return:
    """
    # 渲染数据
    header_title, path1, path2 = "Sudo命令", "别名管理", "查看别名"

    # 获取所有sudo 命令别名
    sudos_list = PermSudo.objects.all()

    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if keyword:
        sudos_list = sudos_list.filter(Q(name=keyword))

    sudos_list, p, sudos, page_range, current_page, show_first, show_end = pages(sudos_list, request)

    return my_render('jperm/perm_sudo_list.html', locals(), request)
示例#33
0
def perm_role_list(request):
    """
    list role page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "查看系统用户"

    # 获取所有系统角色
    roles_list = PermRole.objects.all()
    role_id = request.GET.get('id')
    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if keyword:
        roles_list = roles_list.filter(Q(name=keyword))

    if role_id:
        roles_list = roles_list.filter(id=role_id)

    roles_list, p, roles, page_range, current_page, show_first, show_end = pages(roles_list, request)

    return my_render('jperm/perm_role_list.html', locals(), request)
示例#34
0
def perm_rule_list(request):
    """
    list rule page
    授权规则列表
    """
    # 渲染数据
    header_title, path1, path2 = "授权规则", "规则管理", "查看规则"
    # 获取所有规则
    rules_list = PermRule.objects.all()
    rule_id = request.GET.get('id')
    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if rule_id:
        rules_list = rules_list.filter(id=rule_id)

    if keyword:
        rules_list = rules_list.filter(Q(name__icontains=keyword))

    rules_list, p, rules, page_range, current_page, show_first, show_end = pages(rules_list, request)

    return my_render('jperm/perm_rule_list.html', locals(), request)
示例#35
0
def perm_role_list(request):
    """
    list role page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "查看系统用户"

    # 获取所有系统角色
    roles_list = PermRole.objects.all()
    role_id = request.GET.get('id')
    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if keyword:
        roles_list = roles_list.filter(Q(name=keyword))

    if role_id:
        roles_list = roles_list.filter(id=role_id)

    roles_list, p, roles, page_range, current_page, show_first, show_end = pages(roles_list, request)

    return my_render('jperm/perm_role_list.html', locals(), request)
示例#36
0
def perm_rule_list(request):
    """
    list rule page
    授权规则列表
    """
    # 渲染数据
    header_title, path1, path2 = "授权规则", "规则管理", "查看规则"
    # 获取所有规则
    rules_list = PermRule.objects.all()
    rule_id = request.GET.get('id')
    # TODO: 搜索和分页
    keyword = request.GET.get('search', '')
    if rule_id:
        rules_list = rules_list.filter(id=rule_id)

    if keyword:
        rules_list = rules_list.filter(Q(name=keyword))

    rules_list, p, rules, page_range, current_page, show_first, show_end = pages(rules_list, request)

    return my_render('jperm/perm_rule_list.html', locals(), request)
示例#37
0
def user_list(request):
    user_role = {'SU': '超级管理员', 'GA': '组管理员', 'CU': '普通用户'}
    header_title, path1, path2 = '查看用户', '用户管理', '用户列表'
    keyword = request.GET.get('keyword', '')
    gid = request.GET.get('gid', '')
    users_list = User.objects.all().order_by('username')

    if gid:
        user_group = UserGroup.objects.filter(id=gid)
        if user_group:
            user_group = user_group[0]
            users_list = user_group.user_set.all()

    if keyword:
        users_list = users_list.filter(
            Q(username__icontains=keyword)
            | Q(name__icontains=keyword)).order_by('username')

    users_list, p, users, page_range, current_page, show_first, show_end = pages(
        users_list, request)

    return my_render('juser/user_list.html', locals(), request)
示例#38
0
def perm_role_push(request):
    """
    the role push page
    """
    # 渲染数据
    header_title, path1, path2 = "系统用户", "系统用户管理", "系统用户推送"
    role_id = request.GET.get('id')
    asset_ids = request.GET.get('asset_id')
    role = get_object(PermRole, id=role_id)
    assets = Asset.objects.all()
    asset_groups = AssetGroup.objects.all()
    if asset_ids:
        need_push_asset = [get_object(Asset, id=asset_id) for asset_id in asset_ids.split(',')]

    if request.method == "POST":
        # 获取推荐角色的名称列表
        # 计算出需要推送的资产列表
        asset_ids = request.POST.getlist("assets")
        asset_group_ids = request.POST.getlist("asset_groups")
        assets_obj = [Asset.objects.get(id=asset_id) for asset_id in asset_ids]
        asset_groups_obj = [AssetGroup.objects.get(id=asset_group_id) for asset_group_id in asset_group_ids]
        group_assets_obj = []
        for asset_group in asset_groups_obj:
            group_assets_obj.extend(asset_group.asset_set.all())
        calc_assets = list(set(assets_obj) | set(group_assets_obj))

        push_resource = gen_resource(calc_assets)

        # 调用Ansible API 进行推送
        password_push = True if request.POST.get("use_password") else False
        key_push = True if request.POST.get("use_publicKey") else False
        task = MyTask(push_resource)
        ret = {}

        # 因为要先建立用户,而push key是在 password也完成的情况下的 可选项
        # 1. 以秘钥 方式推送角色
        if key_push:
            ret["pass_push"] = task.add_user(role.name)
            ret["key_push"] = task.push_key(role.name, os.path.join(role.key_path, 'id_rsa.pub'))

        # 2. 推送账号密码 <为了安全 系统用户统一使用秘钥进行通信, 不再提供密码方式的推送>
        # elif password_push:
        #     ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password))

        # 3. 推送sudo配置文件
        if key_push:
            sudo_list = set([sudo for sudo in role.sudo.all()])  # set(sudo1, sudo2, sudo3)
            if sudo_list:
                ret['sudo'] = task.push_sudo_file([role], sudo_list)

        logger.debug('推送role结果: %s' % ret)
        success_asset = {}
        failed_asset = {}
        logger.debug(ret)
        for push_type, result in ret.items():
            if result.get('failed'):
                for hostname, info in result.get('failed').items():
                    if hostname in failed_asset.keys():
                        if info in failed_asset.get(hostname):
                            failed_asset[hostname] += info
                    else:
                        failed_asset[hostname] = info

        for push_type, result in ret.items():
            if result.get('ok'):
                for hostname, info in result.get('ok').items():
                    if hostname in failed_asset.keys():
                        continue
                    elif hostname in success_asset.keys():
                        if str(info) in success_asset.get(hostname, ''):
                            success_asset[hostname] += str(info)
                    else:
                        success_asset[hostname] = str(info)

        # 推送成功 回写push表
        for asset in calc_assets:
            push_check = PermPush.objects.filter(role=role, asset=asset)
            if push_check:
                func = push_check.update
            else:
                def func(**kwargs):
                    PermPush(**kwargs).save()

            if failed_asset.get(asset.hostname):
                func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=False,
                     result=failed_asset.get(asset.hostname))
            else:
                func(is_password=password_push, is_public_key=key_push, role=role, asset=asset, success=True)

        if not failed_asset:
            msg = u'系统用户 %s 推送成功[ %s ]' % (role.name, ','.join(success_asset.keys()))
        else:
            error = u'系统用户 %s 推送失败 [ %s ], 推送成功 [ %s ] 进入系统用户详情,查看失败原因' % (role.name,
                                                                ','.join(failed_asset.keys()),
                                                                ','.join(success_asset.keys()))
    return my_render('jperm/perm_role_push.html', locals(), request)
示例#39
0
文件: views.py 项目: Gwill/jumpserver
            user_group_obj = rule_obj.user_group.all()
            asset_obj = rule_obj.asset.all()
            asset_group_obj = rule_obj.asset_group.all()
            roles_name = [role.name for role in rule_obj.role.all()]

            # 渲染数据
            roles_name = ",".join(roles_name)
            rule = rule_obj
            users = user_obj
            user_groups = user_group_obj
            assets = asset_obj
            asset_groups = asset_group_obj
    except ServerError, e:
        logger.warning(e)

    return my_render("jperm/perm_rule_detail.html", locals(), request)


def perm_rule_add(request):
    """
    add rule page
    添加授权
    """
    # 渲染数据
    header_title, path1, path2 = "授权规则", "规则管理", "添加规则"

    # 渲染数据, 获取所有 用户,用户组,资产,资产组,用户角色, 用于添加授权规则
    users = User.objects.all()
    user_groups = UserGroup.objects.all()
    assets = Asset.objects.all()
    asset_groups = AssetGroup.objects.all()
示例#40
0
            user_group_obj = rule_obj.user_group.all()
            asset_obj = rule_obj.asset.all()
            asset_group_obj = rule_obj.asset_group.all()
            roles_name = [role.name for role in rule_obj.role.all()]

            # 渲染数据
            roles_name = ','.join(roles_name)
            rule = rule_obj
            users = user_obj
            user_groups = user_group_obj
            assets = asset_obj
            asset_groups = asset_group_obj
    except ServerError, e:
        logger.warning(e)

    return my_render('jperm/perm_rule_detail.html', locals(), request)


def perm_rule_add(request):
    """
    add rule page
    添加授权
    """
    # 渲染数据
    header_title, path1, path2 = "授权规则", "规则管理", "添加规则"

    # 渲染数据, 获取所有 用户,用户组,资产,资产组,用户角色, 用于添加授权规则
    users = User.objects.all()
    user_groups = UserGroup.objects.all()
    assets = Asset.objects.all()
    asset_groups = AssetGroup.objects.all()