예제 #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('upperm/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", "")

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

            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
예제 #2
0
파일: views.py 프로젝트: gyw040518/utopia
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('upperm/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", "")

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

            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
예제 #3
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", "")
        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'))
예제 #4
0
파일: connect.py 프로젝트: funthing/utopia
 def get_connect_info(self):
     """
     获取需要登陆的主机的信息和映射用户的账号密码
     """
     asset_info = get_asset_info(self.asset)
     role_key = get_role_key(self.user, self.role)  # 获取角色的key,因为ansible需要权限是600,所以统一生成用户_角色key
     role_pass = CRYPTOR.decrypt(self.role.password)
     connect_info = {'user': self.user, 'asset': self.asset, 'ip': asset_info.get('ip'),
                     'port': int(asset_info.get('port')), 'role_name': self.role.name,
                     'role_pass': role_pass, 'role_key': role_key}
     logger.debug(connect_info)
     return connect_info
예제 #5
0
파일: views.py 프로젝트: gyw040518/utopia
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", "")
        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'))
예제 #6
0
파일: connect.py 프로젝트: gyw040518/utopia
 def get_connect_info(self):
     """
     获取需要登陆的主机的信息和映射用户的账号密码
     """
     asset_info = get_asset_info(self.asset)
     role_key = get_role_key(self.user, self.role)  # 获取角色的key,因为ansible需要权限是600,所以统一生成用户_角色key
     role_pass = CRYPTOR.decrypt(self.role.password)
     connect_info = {
         "user": self.user,
         "asset": self.asset,
         "ip": asset_info.get("ip"),
         "port": int(asset_info.get("port")),
         "role_name": self.role.name,
         "role_pass": role_pass,
         "role_key": role_key,
     }
     logger.debug(connect_info)
     return connect_info
예제 #7
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 = {}

        # 因为要先建立用户,所以password 是必选项,而push key是在 password也完成的情况下的 可选项
        # 1. 以秘钥 方式推送角色
        if key_push:
            ret["pass_push"] = task.add_user(role.name,
                                             CRYPTOR.decrypt(role.password))
            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 password_push or 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('upperm/perm_role_push.html', locals(), request)
예제 #8
0
파일: views.py 프로젝트: gyw040518/utopia
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 = {}

        # 因为要先建立用户,所以password 是必选项,而push key是在 password也完成的情况下的 可选项
        # 1. 以秘钥 方式推送角色
        if key_push:
            ret["pass_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password))
            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 password_push or 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('upperm/perm_role_push.html', locals(), request)
예제 #9
0
파일: utils.py 프로젝트: funthing/utopia
def get_rand_pass():
    """
    get a reandom password.
    """
    CRYPTOR.gen_rand_pass(20)