From 7cafbde5b125c898758b7aa4a04dc922c1cc4fde Mon Sep 17 00:00:00 2001 From: yumaojun <719118794@qq.com> Date: Mon, 30 Nov 2015 22:55:40 +0800 Subject: [PATCH 1/6] update sudo --- jperm/ansible_api.py | 24 ++++++------------------ jperm/views.py | 5 ++--- templates/jperm/role_sudo.j2 | 27 +++++++++++++++++++++++---- 3 files changed, 31 insertions(+), 25 deletions(-) diff --git a/jperm/ansible_api.py b/jperm/ansible_api.py index 5ce5fe35f..e0585c9dc 100644 --- a/jperm/ansible_api.py +++ b/jperm/ansible_api.py @@ -248,6 +248,7 @@ class Tasks(Command): forks=10, group='default_group', pattern='*', + become=False, ): """ run command from andible ad-hoc. @@ -261,7 +262,7 @@ class Tasks(Command): subset=group, pattern=pattern, forks=forks, - become=False, + become=become, ) self.results = hoc.run() @@ -324,7 +325,7 @@ class Tasks(Command): """ encrypt_pass = sha512_crypt.encrypt(password) module_args = 'name=%s shell=/bin/bash password=%s' % (username, encrypt_pass) - self.__run(module_args, "user") + self.__run(module_args, "user", become=True) return {"status": "failed", "msg": self.msg} if self.msg else {"status": "ok"} @@ -402,7 +403,7 @@ class Tasks(Command): default_mac is string product_name is string """ - self.__run('', 'setup') + self.__run('', 'setup', become=True) result = {} all = self.results.get("contacted") @@ -439,21 +440,8 @@ class Tasks(Command): :return: """ module_args1 = file_path - ret1 = self.__run(module_args1, "script") - module_args2 = 'visudo -c | grep "parsed OK" &> /dev/null && echo "ok" || echo "failed"' - ret2 = self.__run(module_args2, "shell") - ret2_status = [host_value.get("stdout") for host_value in ret2["result"]["contacted"].values()] - - result = {} - if not ret1["msg"]: - result["step1"] = "ok" - else: - result["step1"] = "failed" - - if not ret2["msg"] and "failed" not in ret2_status: - result["step2"] = "ok" - else: - result["step2"] = "failed" + result = self.__run(module_args1, "script") + print result return result diff --git a/jperm/views.py b/jperm/views.py index 689515d7d..62d1c1ad0 100644 --- a/jperm/views.py +++ b/jperm/views.py @@ -463,9 +463,8 @@ def perm_role_push(request): add_sudo_script = get_add_sudo_script(role_chosen_aliase, sudo_alias) ret_sudo = task.push_sudo_file(add_sudo_script) - if ret_sudo["step1"] != "ok" or ret_sudo["step2"] != "ok": - ret_failed["step3"] = "failed" - os.remove(add_sudo_script) + print add_sudo_script + # os.remove(add_sudo_script) print ret diff --git a/templates/jperm/role_sudo.j2 b/templates/jperm/role_sudo.j2 index 1304cb690..79e31226e 100644 --- a/templates/jperm/role_sudo.j2 +++ b/templates/jperm/role_sudo.j2 @@ -2,8 +2,12 @@ sudo_file=/etc/sudoers +sudo_file_bak=/etc/sudoers.bak +# Backup sudoers file +cp ${sudo_file} ${sudo_file_bak} + # Add Command Aliases add_cmd_alias() { {% for sudo in sudo_alias %} @@ -16,18 +20,33 @@ add_cmd_alias() { } +# Add Command Aliases to role add_role_chosen() { {% for role, sudos in role_chosen_aliase.items %} {% for sudo in sudos %} - if $(grep '^{{ role }}.*sudo.name' ${sudo_file} &> /dev/null); then - sed -i 's@^{{ role }}.*sudo.name@{{ role }} ALL = ({{ sudo.runas }}) NOPASSWD: {{ sudo.name }}@g' ${sudo_file} + if $(grep '^{{ role }}.*{{ sudo.name }}' ${sudo_file} &> /dev/null); then + sed -i 's@^{{ role }}.*{{ sudo.name }}@{{ role }} ALL = NOPASSWD: {{ sudo.name }}@g' ${sudo_file} else - echo "{{ role }} ALL = ({{ sudo.runas }}) NOPASSWD: {{ sudo.name }}" >> ${sudo_file} + echo "{{ role }} ALL = NOPASSWD: {{ sudo.name }}" >> ${sudo_file} fi {% endfor %} {% endfor %} } +# Check sudoers file configured correctly +check_sudo_file() { + status=$(visudo -c &> /dev/null && echo "ok" || echo "failed") + if [ ${status} == "failed" ]; then + mv ${sudo_file_bak} ${sudo_file} + ret="failed" + else + ret="ok" + fi +} + add_cmd_alias -add_role_chosen \ No newline at end of file +add_role_chosen +check_sudo_file + +echo ${ret} \ No newline at end of file From bf98aa54642f6485d62a4dec2b1cccf2ac5a487c Mon Sep 17 00:00:00 2001 From: yumaojun <719118794@qq.com> Date: Tue, 1 Dec 2015 11:20:43 +0800 Subject: [PATCH 2/6] sudo push --- jperm/ansible_api.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jperm/ansible_api.py b/jperm/ansible_api.py index 27d61f0e9..3d292a67f 100644 --- a/jperm/ansible_api.py +++ b/jperm/ansible_api.py @@ -286,7 +286,7 @@ class Tasks(Command): push the ssh authorized key to target. """ module_args = 'user="%s" key="{{ lookup("file", "%s") }}" state=present' % (user, key_path) - self.__run(module_args, "authorized_key") + self.__run(module_args, "authorized_key", become=True) return {"status": "failed", "msg": self.msg} if self.msg else {"status": "ok"} @@ -329,7 +329,7 @@ class Tasks(Command): module_args = 'name=%s shell=/bin/bash password=%s' % (username, encrypt_pass) else: module_args = 'name=%s shell=/bin/bash' % username - self.__run(module_args, "user") + self.__run(module_args, "user", become=True) return {"status": "failed", "msg": self.msg} if self.msg else {"status": "ok"} From 8723d673d7475992044c661a912dd361e0540bf0 Mon Sep 17 00:00:00 2001 From: yumaojun <719118794@qq.com> Date: Sun, 6 Dec 2015 18:07:57 +0800 Subject: [PATCH 3/6] =?UTF-8?q?1.=20=E8=AE=A1=E7=AE=97=E8=AF=A5=E8=A7=92?= =?UTF-8?q?=E8=89=B2=E6=9C=89=E5=93=AA=E4=BA=9B=E4=B8=BB=E6=9C=BA=E6=B2=A1?= =?UTF-8?q?=E6=8E=A8=E9=80=81=E6=97=B6=EF=BC=8C=E4=BD=BF=E7=94=A8=E4=BA=A4?= =?UTF-8?q?=E9=9B=86=E8=AE=A1=E7=AE=97=EF=BC=88=E5=8E=9F=E6=9D=A5=E6=98=AF?= =?UTF-8?q?=E5=B7=AE=E9=9B=86=EF=BC=89=202.=20=E4=BF=AE=E6=94=B9rule=20=20?= =?UTF-8?q?=20detail=E9=A1=B5=E9=9D=A2=E3=80=80=E4=B8=8D=E8=AE=A1=E7=AE=97?= =?UTF-8?q?=EF=BC=8C=E7=BB=8F=E8=BF=94=E5=9B=9Erule=20=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E7=9A=84=E4=BF=A1=E6=81=AF=203.=20=E4=BF=AE=E6=94=B9role=20=20?= =?UTF-8?q?=20detail=E9=A1=B5=E9=9D=A2=E3=80=80=E4=B8=8D=E8=AE=A1=E7=AE=97?= =?UTF-8?q?=EF=BC=8C=E7=BB=8F=E8=BF=94=E5=9B=9Erule=20=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E7=9A=84=E4=BF=A1=E6=81=AF=204.=20=E6=B7=BB=E5=8A=A0=E4=BA=86?= =?UTF-8?q?=20=E6=8E=A8=E9=80=81=E4=B8=BB=E6=9C=BA=E4=B8=8A=E7=9A=84?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E5=9B=9E=E6=94=B6=E5=8A=9F=E8=83=BD=205.=20T?= =?UTF-8?q?ODO:=20=20=E9=A1=B5=E9=9D=A2=E7=9A=84=E7=BE=8E=E8=A7=82?= =?UTF-8?q?=E5=B1=95=E7=A4=BA=EF=BC=8C=E4=B8=8E=E3=80=80=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E3=80=80=E7=94=A8=E6=88=B7=E7=9A=84=E6=89=B9=E9=87=8F=E5=9B=9E?= =?UTF-8?q?=E6=94=B6=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- jperm/perm_api.py | 18 +++++------------- jperm/views.py | 21 +++++++++++++++++++-- templates/jperm/perm_role_detail.html | 2 +- templates/jperm/perm_rule_detail.html | 17 +++++++++++------ 4 files changed, 36 insertions(+), 22 deletions(-) diff --git a/jperm/perm_api.py b/jperm/perm_api.py index 080f1cb39..592cdb22a 100644 --- a/jperm/perm_api.py +++ b/jperm/perm_api.py @@ -224,9 +224,7 @@ def get_role_info(role_id, type="all"): users_obj = [] assets_obj = [] user_groups_obj = [] - group_users_obj = [] asset_groups_obj = [] - group_assets_obj = [] for rule in rules_obj: for user in rule.user.all(): users_obj.append(user) @@ -234,31 +232,25 @@ def get_role_info(role_id, type="all"): assets_obj.append(asset) for user_group in rule.user_group.all(): user_groups_obj.append(user_group) - for user in user_group.user_set.all(): - group_users_obj.append(user) for asset_group in rule.asset_group.all(): asset_groups_obj.append(asset_group) - for asset in asset_group.asset_set.all(): - group_assets_obj.append(asset) - - calc_users = set(users_obj) | set(group_users_obj) - calc_assets = set(assets_obj) | set(group_assets_obj) if type == "all": return {"rules": rules_obj, - "users": list(calc_users), + "users": users_obj, "user_groups": user_groups_obj, - "assets": list(calc_assets), + "assets": assets_obj, "asset_groups": asset_groups_obj, } + elif type == "rule": return rules_obj elif type == "user": - return calc_users + return users_obj elif type == "user_group": return user_groups_obj elif type == "asset": - return calc_assets + return assets_obj elif type == "asset_group": return asset_groups_obj else: diff --git a/jperm/views.py b/jperm/views.py index 12ca395ba..bd6193da1 100644 --- a/jperm/views.py +++ b/jperm/views.py @@ -50,14 +50,19 @@ def perm_rule_detail(request): rule_id = request.GET.get("id") rule_obj = PermRule.objects.get(id=rule_id) user_obj = rule_obj.user.all() + usergroup_obj = rule_obj.user_group.all() asset_obj = rule_obj.asset.all() + assetgroup_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 = usergroup_obj assets = asset_obj + asset_groups = assetgroup_obj return my_render('jperm/perm_rule_detail.html', locals(), request) @@ -108,7 +113,8 @@ def perm_rule_add(request): 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)) + print set(calc_assets), set(asset_no_push) + need_push_asset.update(set(calc_assets) & set(asset_no_push)) if need_push_asset: raise ServerError(u'没有推送角色 %s 的主机 %s' % (role.name, ','.join([asset.hostname for asset in need_push_asset]))) @@ -256,7 +262,7 @@ def perm_role_add(request): try: if get_object(PermRole, name=name): - raise ServerError('已经存在该用户 %s' % name) + raise ServerError(u'已经存在该用户 %s' % name) default = get_object(Setting, name='default') if password: @@ -579,10 +585,21 @@ def perm_sudo_delete(request): def perm_role_recycle(request): role_id = request.GET.get('role_id') asset_ids = request.GET.get('asset_id').split(',') + success = request.GET.get("success") + print request.GET + + if success == "True": + assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids] + recycle_resource = gen_resource(assets) + task = Tasks(recycle_resource) + msg = task.del_user(get_object(PermRole, id=role_id).name) + print msg + for asset_id in asset_ids: asset = get_object(Asset, id=asset_id) role = get_object(PermRole, id=role_id) PermPush.objects.filter(asset=asset, role=role).delete() + return HttpResponse('删除成功') diff --git a/templates/jperm/perm_role_detail.html b/templates/jperm/perm_role_detail.html index 757ec08f2..9d93dde61 100644 --- a/templates/jperm/perm_role_detail.html +++ b/templates/jperm/perm_role_detail.html @@ -198,7 +198,7 @@ {% else %} {{ info.success | yesno:"成功,失败,未知" }} {% endif %} - + {% endfor %} diff --git a/templates/jperm/perm_rule_detail.html b/templates/jperm/perm_rule_detail.html index c2e362b75..8f1b7167b 100644 --- a/templates/jperm/perm_rule_detail.html +++ b/templates/jperm/perm_rule_detail.html @@ -93,12 +93,15 @@ - {% for user in users %} + {% for user in users %} {{ user.name }} - {{ user | user_which_groups:"group" }} + {% endfor %} + {% for group in user_groups %} + {{ group.name }} + {% endfor %} - {% endfor %} + @@ -139,12 +142,14 @@ - {% for asset in assets %} + {% for asset in assets %} {{ asset.ip }} - {{ asset | asset_which_groups:"group" }} + {% endfor %} + {% for group in asset_groups %} + {{ group.name }} + {% endfor %} - {% endfor %} From 58082179fe9d56b2bf855a5586c69530c2450a43 Mon Sep 17 00:00:00 2001 From: yumaojun <719118794@qq.com> Date: Sun, 6 Dec 2015 23:44:13 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=EF=BC=91.=20=E7=94=A8=E6=88=B7=E7=9A=84?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E5=9B=9E=E6=94=B6,=20=E8=A7=92=E8=89=B2?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=BC=9A=E5=9B=9E=E6=94=B6=E6=8E=A8=E9=80=81?= =?UTF-8?q?=E7=9A=84=E8=A7=92=E8=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- jperm/perm_api.py | 16 ++++++------- jperm/views.py | 34 ++++++++++++++++++++------- templates/jperm/perm_role_detail.html | 2 +- 3 files changed, 35 insertions(+), 17 deletions(-) diff --git a/jperm/perm_api.py b/jperm/perm_api.py index 592cdb22a..1f64a0ecd 100644 --- a/jperm/perm_api.py +++ b/jperm/perm_api.py @@ -218,25 +218,25 @@ def get_role_info(role_id, type="all"): """ # 获取role对应的授权规则 role_obj = PermRole.objects.get(id=role_id) - rules_obj = role_obj.perm_rule.all() + rule_push_obj = role_obj.perm_rule.all() # 获取role 对应的用户 和 用户组 # 获取role 对应的主机 和主机组 users_obj = [] assets_obj = [] user_groups_obj = [] asset_groups_obj = [] - for rule in rules_obj: - for user in rule.user.all(): + for push in rule_push_obj: + for user in push.user.all(): users_obj.append(user) - for asset in rule.asset.all(): + for asset in push.asset.all(): assets_obj.append(asset) - for user_group in rule.user_group.all(): + for user_group in push.user_group.all(): user_groups_obj.append(user_group) - for asset_group in rule.asset_group.all(): + for asset_group in push.asset_group.all(): asset_groups_obj.append(asset_group) if type == "all": - return {"rules": rules_obj, + return {"rules": rule_push_obj, "users": users_obj, "user_groups": user_groups_obj, "assets": assets_obj, @@ -244,7 +244,7 @@ def get_role_info(role_id, type="all"): } elif type == "rule": - return rules_obj + return rule_push_obj elif type == "user": return users_obj elif type == "user_group": diff --git a/jperm/views.py b/jperm/views.py index bd6193da1..e96c0b010 100644 --- a/jperm/views.py +++ b/jperm/views.py @@ -297,12 +297,25 @@ def perm_role_delete(request): role_id = request.POST.get("id") role = PermRole.objects.get(id=role_id) role_key = role.key_path + + # 删除推送到主机上的role + recycle_assets = [push.asset for push in role.perm_push.all() if push.success] + print recycle_assets + + if recycle_assets: + recycle_resource = gen_resource(recycle_assets) + task = Tasks(recycle_resource) + msg = task.del_user(get_object(PermRole, id=role_id).name) + # TODO: 判断返回结果,处理异常 + print msg + # 删除存储的秘钥,以及目录 key_files = os.listdir(role_key) for key_file in key_files: os.remove(os.path.join(role_key, key_file)) os.rmdir(role_key) - # 数据库里删除记录 + + # 数据库里删除记录 TODO: 判断返回结果,处理异常 role.delete() return HttpResponse(u"删除角色: %s" % role.name) else: @@ -585,15 +598,20 @@ def perm_sudo_delete(request): def perm_role_recycle(request): role_id = request.GET.get('role_id') asset_ids = request.GET.get('asset_id').split(',') - success = request.GET.get("success") print request.GET - if success == "True": - assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids] - recycle_resource = gen_resource(assets) - task = Tasks(recycle_resource) - msg = task.del_user(get_object(PermRole, id=role_id).name) - print msg + 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 = Tasks(recycle_resource) + msg = task.del_user(get_object(PermRole, id=role_id).name) + # TODO: 判断返回结果,处理异常 + print msg for asset_id in asset_ids: asset = get_object(Asset, id=asset_id) diff --git a/templates/jperm/perm_role_detail.html b/templates/jperm/perm_role_detail.html index 9d93dde61..757ec08f2 100644 --- a/templates/jperm/perm_role_detail.html +++ b/templates/jperm/perm_role_detail.html @@ -198,7 +198,7 @@ {% else %} {{ info.success | yesno:"成功,失败,未知" }} {% endif %} - + {% endfor %} From 49267b57e450cc9e53bb497c35ddb49645b162a2 Mon Sep 17 00:00:00 2001 From: yumaojun <719118794@qq.com> Date: Thu, 10 Dec 2015 00:10:39 +0800 Subject: [PATCH 5/6] =?UTF-8?q?1.=20=E8=A7=92=E8=89=B2=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=92=8C=E8=A7=92=E8=89=B2=E4=BF=AE=E6=94=B9,=20Server=20?= =?UTF-8?q?=E7=AB=AF=E3=80=80=E8=BE=93=E5=85=A5=E9=AA=8C=E8=AF=81=202.=20?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- jperm/ansible_api.py | 2 +- jperm/perm_api.py | 4 - jperm/views.py | 187 ++++++++++++++++++++++++++----------------- jumpserver/api.py | 4 +- 4 files changed, 118 insertions(+), 79 deletions(-) diff --git a/jperm/ansible_api.py b/jperm/ansible_api.py index bcd64dee8..7a3af1f27 100644 --- a/jperm/ansible_api.py +++ b/jperm/ansible_api.py @@ -261,7 +261,7 @@ class Tasks(Command): subset=group, pattern=pattern, forks=forks, - become=False, + become=True, ) self.results = hoc.run() diff --git a/jperm/perm_api.py b/jperm/perm_api.py index 1f64a0ecd..2c63450ca 100644 --- a/jperm/perm_api.py +++ b/jperm/perm_api.py @@ -276,7 +276,3 @@ def get_role_push_host(role): if __name__ == "__main__": print get_role_info(1) - - - - diff --git a/jperm/views.py b/jperm/views.py index e96c0b010..a26289c6a 100644 --- a/jperm/views.py +++ b/jperm/views.py @@ -3,19 +3,22 @@ from django.db.models import Q from paramiko import SSHException from jperm.perm_api import * -from juser.user_api import gen_ssh_key from juser.models import User, UserGroup from jasset.models import Asset, AssetGroup from jperm.models import PermRole, PermRule, PermSudo, PermPush from jumpserver.models import Setting -from jperm.utils import updates_dict, gen_keys, get_rand_pass, get_add_sudo_script +from jperm.utils import gen_keys, get_add_sudo_script from jperm.ansible_api import Tasks from jperm.perm_api import get_role_info, get_role_push_host from jumpserver.api import my_render, get_object, CRYPTOR +# 设置Perm APP Log +from jumpserver.settings import LOG_LEVEL +logger = set_log(LOG_LEVEL, filename='jumpserver_perm.log') + @require_role('admin') def perm_rule_list(request): @@ -32,7 +35,6 @@ def perm_rule_list(request): keyword = request.GET.get('search', '') 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) @@ -92,23 +94,30 @@ def perm_rule_add(request): rule_comment = request.POST.get('rule_comment') try: + # 用户输入验证 rule = get_object(PermRule, name=rule_name) + # 用户输入验证 if rule: raise ServerError(u'授权规则 %s 已存在' % rule_name) + if not users_select and not user_groups_select: + raise ServerError(u"用户和用户组 必选1个") + if not assets_select and not asset_groups_select: + raise ServerError(u"资产和资产组 必选1个") + if 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 = [asset for asset in [group.asset_set.all() for group in asset_groups_obj]] calc_assets = set(group_assets_obj) | set(assets_obj) + logger.debug(u"add rule %s| total assets: %s" % (rule_name, calc_assets)) # 获取需要授权的用户列表 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] - # group_users_obj = [user for user in [group.user_set.all() for group in user_groups_obj]] - # calc_users = set(group_users_obj) | set(users_obj) - # 获取授予的角色列表 + # 获取授予的角色列表(角色必选事先已经推送) roles_obj = [PermRole.objects.get(id=role_id) for role_id in roles_select] need_push_asset = set() for role in roles_obj: @@ -116,9 +125,13 @@ def perm_rule_add(request): print set(calc_assets), set(asset_no_push) need_push_asset.update(set(calc_assets) & set(asset_no_push)) if need_push_asset: + logger.warning(u"add rule %s| need_push_asset: %s" % (rule_name, need_push_asset)) raise ServerError(u'没有推送角色 %s 的主机 %s' % (role.name, ','.join([asset.hostname for asset in need_push_asset]))) + # 写会数据库前记录日志 + logger.debug(u"add rule %s| user: %s, user_group: %s, asset: %s, asset_group: %s, role: %s" % ( + rule_name, users_obj, user_groups_obj, assets_obj, asset_groups_obj, roles_obj)) # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色) rule = PermRule(name=rule_name, comment=rule_comment) rule.save() @@ -144,61 +157,77 @@ def perm_rule_edit(request): # 渲染数据 header_title, path1, path2 = "授权规则", "规则管理", "添加规则" - # 根据rule_id 取得rule对象 - rule_id = request.GET.get("id") - rule = PermRule.objects.get(id=rule_id) + try: + # 根据rule_id 取得rule对象 + rule_id = request.GET.get("id") + rule = get_object(PermRule, id=rule_id) + if not rule: + logger.info(u"edit rule %s| rule ready exist: %s" % (rule.name, rule.name)) + raise ServerError(u"授权规则: %s 不存在" % rule.name) - if request.method == 'GET' and rule_id: - # 渲染数据, 获取所选的rule对象 - rule_comment = rule.comment - users_select = rule.user.all() - user_groups_select = rule.user_group.all() - assets_select = rule.asset.all() - asset_groups_select = rule.asset_group.all() - roles_select = rule.role.all() + if request.method == 'GET': + # 渲染数据, 获取所选的rule对象 + rule_comment = rule.comment + users_select = rule.user.all() + user_groups_select = rule.user_group.all() + assets_select = rule.asset.all() + asset_groups_select = rule.asset_group.all() + roles_select = rule.role.all() - users = User.objects.all() - user_groups = UserGroup.objects.all() - assets = Asset.objects.all() - asset_groups = AssetGroup.objects.all() - roles = PermRole.objects.all() - return my_render('jperm/perm_rule_edit.html', locals(), request) + users = User.objects.all() + user_groups = UserGroup.objects.all() + assets = Asset.objects.all() + asset_groups = AssetGroup.objects.all() + roles = PermRole.objects.all() + return my_render('jperm/perm_rule_edit.html', locals(), request) - elif request.method == 'POST' and rule_id: - # 获取用户选择的 用户,用户组,资产,资产组,用户角色 - rule_name = request.POST.get('rule_name') - rule_comment = request.POST.get("rule_comment") - users_select = request.POST.getlist('user', []) - user_groups_select = request.POST.getlist('usergroup', []) - assets_select = request.POST.getlist('asset', []) - asset_groups_select = request.POST.getlist('assetgroup', []) - roles_select = request.POST.getlist('role', []) + elif request.method == 'POST' and rule_id: + # 获取用户选择的 用户,用户组,资产,资产组,用户角色 + rule_name = request.POST.get('rule_name') + rule_comment = request.POST.get("rule_comment") + users_select = request.POST.getlist('user', []) + user_groups_select = request.POST.getlist('usergroup', []) + assets_select = request.POST.getlist('asset', []) + asset_groups_select = request.POST.getlist('assetgroup', []) + roles_select = request.POST.getlist('role', []) - 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 = [asset for asset in [group.asset_set.all() for group in asset_groups_obj]] - # calc_assets = set(group_assets_obj) | set(assets_obj) + # 用户输入验证 + if not users_select and not user_groups_select: + raise ServerError(u"用户和用户组 必选1个") + if not assets_select and not asset_groups_select: + raise ServerError(u"资产和资产组 必选1个") + if not roles_select: + raise ServerError(u"角色 必选为必选项") - # 获取需要授权的用户列表 - 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] - # group_users_obj = [user for user in [group.user_set.all() for group in user_groups_obj]] - # calc_users = set(group_users_obj) | set(users_obj) + 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] - # 获取授予的角色列表 - roles_obj = [PermRole.objects.get(id=role_id) for role_id in roles_select] + # 获取需要授权的用户列表 + 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] - # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色) - 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() + # 获取授予的角色列表 + roles_obj = [PermRole.objects.get(id=role_id) for role_id in roles_select] - msg = u"更新授权规则:%s" % rule.name + # 写会数据库前记录日志 + logger.debug(u"edit rule %s| user: %s, user_group: %s, asset: %s, asset_group: %s, role: %s" % ( + rule_name, users_obj, user_groups_obj, assets_obj, asset_groups_obj, roles_obj)) + + # 仅授权成功的,写回数据库(授权规则,用户,用户组,资产,资产组,用户角色) + 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() + + # 更新成功 + msg = u"更新授权规则:%s" % rule.name + + except ServerError, e: + error = e return HttpResponseRedirect('/jperm/rule/') @@ -213,9 +242,8 @@ def perm_rule_delete(request): if request.method == 'POST': # 根据rule_id 取得rule对象 rule_id = request.POST.get("id") - rule_obj = PermRule.objects.get(id=rule_id) - print rule_id, rule_obj - print rule_obj.name + rule_obj = get_object(PermRule, id=rule_id) + logger.debug(u"delete rule %s|" % rule_obj.name) rule_obj.delete() return HttpResponse(u"删除授权规则:%s" % rule_obj.name) else: @@ -262,6 +290,7 @@ def perm_role_add(request): try: if get_object(PermRole, name=name): + logger.warning(u"add role %s| %s ready exist" % (name, name)) raise ServerError(u'已经存在该用户 %s' % name) default = get_object(Setting, name='default') @@ -269,13 +298,14 @@ def perm_role_add(request): encrypt_pass = CRYPTOR.encrypt(password) else: encrypt_pass = CRYPTOR.encrypt(CRYPTOR.gen_rand_pass(20)) + logger.debug(u"add role %s| use rand password" % name) # 生成随机密码,生成秘钥对 sudos_obj = [get_object(PermSudo, id=sudo_id) for sudo_id in sudo_ids] if key_content: key_path = gen_keys(key=key_content) else: key_path = gen_keys() - logger.debug('generate role key: %s' % key_path) + logger.debug(u'add role %s| generate role key: %s' % (name, key_path)) role = PermRole(name=name, comment=comment, password=encrypt_pass, key_path=key_path) role.save() role.sudo = sudos_obj @@ -295,25 +325,26 @@ def perm_role_delete(request): if request.method == "POST": # 获取参数删除的role对象 role_id = request.POST.get("id") - role = PermRole.objects.get(id=role_id) + role = get_object(PermRole, id=role_id) role_key = role.key_path # 删除推送到主机上的role recycle_assets = [push.asset for push in role.perm_push.all() if push.success] - print recycle_assets + logger.debug(u"delete role %s| delete_assets: %s" % (role.name, recycle_assets)) if recycle_assets: recycle_resource = gen_resource(recycle_assets) task = Tasks(recycle_resource) msg = task.del_user(get_object(PermRole, id=role_id).name) + logger.info(u"delete role %s| execute delete user: %s" % (role.name, msg)) # TODO: 判断返回结果,处理异常 - print msg # 删除存储的秘钥,以及目录 key_files = os.listdir(role_key) for key_file in key_files: os.remove(os.path.join(role_key, key_file)) os.rmdir(role_key) + logger.info(u"delete role %s| delete role key directory: %s" % (role.name, role_key)) # 数据库里删除记录 TODO: 判断返回结果,处理异常 role.delete() @@ -381,7 +412,8 @@ def perm_role_edit(request): try: if not role: - raise ServerError('角色用户不能存在') + logger.warning(u"edit role %s| role not exist" % role_name) + raise ServerError('角色用户不存在') if role_password: encrypt_pass = CRYPTOR.encrypt(role_password) @@ -392,7 +424,7 @@ def perm_role_edit(request): 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) + logger.info(u'edit role %s| recreate role key: %s' % (role_name, role.key_path)) # 写入数据库 role.name = role_name role.comment = role_comment @@ -431,7 +463,7 @@ def perm_role_push(request): 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) - logger.debug('Push role res: %s' % push_resource) + logger.debug(u'push role %s| push role res: %s' % (role.name, push_resource)) # 调用Ansible API 进行推送 password_push = True if request.POST.get("use_password") else False @@ -444,12 +476,14 @@ def perm_role_push(request): # 1. 以password 方式推送角色 if password_push: ret["password_push"] = task.add_user(role.name, CRYPTOR.decrypt(role.password)) + logger.info(u"push role %s| 1.1 push password msg: %s" % (role.name, ret)) if ret["password_push"].get("status") != "success": ret_failed = ret["password_push"].get('msg') # 2. 以秘钥 方式推送角色 if key_push: ret["password_push"] = task.add_user(role.name) + logger.info(u"push role %s| 1.2 push public key msg: %s" % (role.name, ret)) if ret["password_push"].get("status") != "ok": ret_failed = ret["password_push"].get('msg') ret["key_push"] = task.push_key(role.name, os.path.join(role.key_path, 'id_rsa.pub')) @@ -463,13 +497,13 @@ def perm_role_push(request): role_chosen_aliase[role.name] = ','.join(sudo.name for sudo in sudo_alias) add_sudo_script = get_add_sudo_script(role_chosen_aliase, sudo_alias) ret['sudo'] = task.push_sudo_file(add_sudo_script) + logger.info(u"push role %s| 2.1 push sudo msg: %s" % (role.name, ret)) if ret['sudo'].get('msg'): ret_failed = ret['sudo'].get('msg') - # os.remove(add_sudo_script) - logger.debug('推送role结果: %s' % ret) - logger.debug('推送role错误: %s' % ret_failed) + logger.info(u'push role %s| 推送role结果: %s' % (role.name, ret)) + logger.info(u'push role %s| 推送role错误: %s' % (role.name, ret_failed)) success_asset = [] failed_asset = [] @@ -496,6 +530,7 @@ def perm_role_push(request): error = u'角色 %s 推送失败 [ %s ], 推送成功 [ %s ]' % (role.name, ','.join([asset.hostname for asset in failed_asset]), ','.join([asset.hostname for asset in success_asset])) + # return HttpResponseRedirect("/jperm/role/perm_role_detail/?id=%s" % role_id) return my_render('jperm/perm_role_push.html', locals(), request) @@ -537,14 +572,17 @@ def perm_sudo_add(request): name = request.POST.get("sudo_name").strip() comment = request.POST.get("sudo_comment").strip() commands = request.POST.get("sudo_commands").strip() + logger.debug(u"add sudo %s| commands: %s" % (name, commands)) if get_object(PermSudo, name=name): - error = 'Sudo别名 %s已经存在' % name + logger.info(u"add sudo %s| ready exists" % name) + error = u'Sudo别名 %s已经存在' % name else: - sudo = PermSudo(name=name.strip(), comment=comment, commands=commands.strip()) + sudo = PermSudo(name=name, comment=comment, commands=commands) sudo.save() msg = u"添加Sudo命令别名: %s" % name - # 渲染数据 + + return HttpResponseRedirect('/jperm/sudo/') return my_render('jperm/perm_sudo_add.html', locals(), request) @@ -571,9 +609,11 @@ def perm_sudo_edit(request): sudo.comment = comment sudo.save() + logger.debug(u"edit sudo %s| commands: %s" % (name, commands)) msg = u"更新命令别名: %s" % name + return HttpResponseRedirect('/jperm/sudo/') - return my_render('jperm/perm_sudo_edit.html', locals(), request) + return my_render(u'jperm/perm_sudo_edit.html', locals(), request) @require_role('admin') @@ -589,6 +629,7 @@ def perm_sudo_delete(request): sudo = PermSudo.objects.get(id=sudo_id) # 数据库里删除记录 sudo.delete() + logger.debug(u"edit sudo %s| " % sudo.name) return HttpResponse(u"删除角色: %s" % sudo.name) else: return HttpResponse(u"不支持该操作") @@ -597,8 +638,8 @@ def perm_sudo_delete(request): @require_role('admin') def perm_role_recycle(request): role_id = request.GET.get('role_id') + role = get_object(PermRole, id=role_id) asset_ids = request.GET.get('asset_id').split(',') - print request.GET assets = [get_object(Asset, id=asset_id) for asset_id in asset_ids] @@ -608,10 +649,12 @@ def perm_role_recycle(request): recycle_assets.append(asset) recycle_resource = gen_resource(recycle_assets) + logger.debug(u"recycle role %s| delete role res: %s" % (role.name, recycle_resource)) + task = Tasks(recycle_resource) msg = task.del_user(get_object(PermRole, id=role_id).name) + logger.info(u"recycle role %s| delete role msg: %s" % (role.name, msg)) # TODO: 判断返回结果,处理异常 - print msg for asset_id in asset_ids: asset = get_object(Asset, id=asset_id) diff --git a/jumpserver/api.py b/jumpserver/api.py index d36b306d2..10c4574de 100644 --- a/jumpserver/api.py +++ b/jumpserver/api.py @@ -26,12 +26,12 @@ from django.shortcuts import render_to_response from django.core.mail import send_mail -def set_log(level): +def set_log(level, filename='jumpserver.log'): """ return a log file object 根据提示设置log打印 """ - log_file = os.path.join(LOG_DIR, 'jumpserver.log') + log_file = os.path.join(LOG_DIR, filename) if not os.path.isfile(log_file): os.mknod(log_file) os.chmod(log_file, 0777) From 1a3541e5752d8d00d9e80b7964f7eb1a64f0c182 Mon Sep 17 00:00:00 2001 From: halcyon <864072399@qq.com> Date: Thu, 10 Dec 2015 00:13:50 +0800 Subject: [PATCH 6/6] fix bugs --- jasset/urls.py | 4 -- jasset/views.py | 3 +- templates/jasset/asset_cu_list.html | 56 +---------------------- templates/jasset/asset_list.html | 2 +- templates/jasset/asset_update_status.html | 45 ++++++++++++++++++ 5 files changed, 48 insertions(+), 62 deletions(-) create mode 100644 templates/jasset/asset_update_status.html diff --git a/jasset/urls.py b/jasset/urls.py index 8fcbcdea4..ab7b6ac10 100644 --- a/jasset/urls.py +++ b/jasset/urls.py @@ -12,15 +12,11 @@ urlpatterns = patterns('', url(r'^asset_edit/$', asset_edit), url(r'^asset_update/$', asset_update), url(r'^asset_update_batch/$', asset_update_batch), - # url(r'^search/$', host_search), - # url(r"^show_all_ajax/$", show_all_ajax), url(r'^group_add/$', group_add), url(r'^group_list/$', group_list), url(r'^group_edit/$', group_edit), url(r'^group_list/$', group_list), - # url(r'^group_del_host/$', group_del_host), url(r'^asset_edit_batch/$', asset_edit_batch), - # url(r'^host_edit_common/batch/$', host_edit_common_batch), url(r'^idc_add/$', idc_add), url(r'^idc_list/$', idc_list), url(r'^idc_edit/$', idc_edit), diff --git a/jasset/views.py b/jasset/views.py index 0d9e07c82..01aa1b7eb 100644 --- a/jasset/views.py +++ b/jasset/views.py @@ -294,7 +294,6 @@ def asset_list(request): asset_find = asset_find.filter(idc__name__contains=idc_name) if group_name: - print asset_find, type(asset_find) asset_find = asset_find.filter(group__name__contains=group_name) if asset_type: @@ -413,7 +412,7 @@ def asset_edit_batch(request): if alert_list: recode_name = unicode(name) + ' - ' + u'批量' AssetRecord.objects.create(asset=asset, username=recode_name, content=alert_list) - return HttpResponse('ok') + return my_render('jasset/asset_update_status.html', locals(), request) return my_render('jasset/asset_edit_batch.html', locals(), request) diff --git a/templates/jasset/asset_cu_list.html b/templates/jasset/asset_cu_list.html index 9d1dd7bf9..49d81e12d 100644 --- a/templates/jasset/asset_cu_list.html +++ b/templates/jasset/asset_cu_list.html @@ -24,61 +24,7 @@
-
- - - - - - - -
- -
+
diff --git a/templates/jasset/asset_list.html b/templates/jasset/asset_list.html index 4124b30d1..428c4bf73 100644 --- a/templates/jasset/asset_list.html +++ b/templates/jasset/asset_list.html @@ -301,7 +301,7 @@ return false; } var url= $(this).attr("value") + '?asset_id_all=' + asset_id_all; - layer.open({ + parent.layer.open({ type: 2, title: 'JumpServer - 批量修改主机', maxmin: true, diff --git a/templates/jasset/asset_update_status.html b/templates/jasset/asset_update_status.html new file mode 100644 index 000000000..e0897b074 --- /dev/null +++ b/templates/jasset/asset_update_status.html @@ -0,0 +1,45 @@ + + + + + + + + + + + + + {% load bootstrap %} + {% block content %} + +
+
+
+
+

+
+
+
+
+ + + {% endblock content %} + + \ No newline at end of file