From 46520287d940daee4444e1a217adf609fe4bc7e6 Mon Sep 17 00:00:00 2001 From: ibuler Date: Thu, 17 May 2018 15:26:22 +0800 Subject: [PATCH] =?UTF-8?q?[Update]=20=E6=B7=BB=E5=8A=A0=E6=B8=85=E7=90=86?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E7=94=A8=E6=88=B7=E7=BB=84=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/clean_duplicate_user_groups.py | 70 ++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 utils/clean_duplicate_user_groups.py diff --git a/utils/clean_duplicate_user_groups.py b/utils/clean_duplicate_user_groups.py new file mode 100644 index 000000000..be8b2d9ec --- /dev/null +++ b/utils/clean_duplicate_user_groups.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# + +import os +import sys +from collections import Counter +import django +from django.db.models import Count + + +if os.path.exists('../apps'): + sys.path.insert(0, '../apps') +elif os.path.exists('./apps'): + sys.path.insert(0, './apps') + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jumpserver.settings") +django.setup() + +from users.models import UserGroup + + +def clean_group(interactive=True): + groups = UserGroup.objects.all() + groups_name_list = groups.values_list('name', flat=True) + groups_with_info = groups.annotate(Count('users'))\ + .annotate(Count('asset_permissions')) + + counter = Counter(groups_name_list) + for name, count in counter.items(): + if count == 0: + continue + groups_duplicate = groups_with_info.filter(name=name) + need_clean_count = groups_duplicate.count() + + for group in groups_duplicate: + need_clean = True + if group.users__count > 0: + need_clean = False + elif group.asset_permissions__count > 0: + need_clean = False + elif need_clean_count == 1: + need_clean = False + + if need_clean: + confirm = True + if interactive: + confirm = False + while True: + confirm = input( + "Delete user group <{}>, create at {}? ([y]/n)".format( + name, group.date_created) + ) + if confirm.lower() == "y": + confirm = True + break + elif confirm.lower() == "n": + confirm = False + break + else: + print("No valid input") + continue + if confirm: + group.delete() + print("Delete success: {}".format(name)) + need_clean_count -= 1 + else: + continue + +if __name__ == '__main__': + clean_group()