嵌套循环在查询中迭代太多次

时间:2019-06-27 17:19:24

标签: python-3.x for-loop pyad

我正在尝试编写一个Python脚本来查询LDAP以获取用户成员身份。然后,我想针对固定的组列表测试那些成员资格,以确定我的用户是否具有那些组的成员资格。

这是我的代码:

    user_identifier = "JohnSmith123"
    group_names = ["Faker1", "Faker2", "MML User"]

    # establish AD query
    q = pyad.adquery.ADQuery()

        q.execute_query(
            attributes=["memberOf"],
            where_clause=f"cn = '{user_identifier}'",
            base_dn="DC=company_name, DC=com"
        )
        for row in q.get_results():
            results = row.get("memberOf")
            groups = str(results).split(',')
            for group in group_names:
                for item in groups:
                    # strip leading characters from item
                    if "CN=" in item:
                        formatted_group = item[5:]
                        if group != formatted_group:
                            print(f"{user_identifier} is not a member of {group}")
                        else:
                            print(f"{user_identifier} is a member of {group}")

这有效,除了我的循环循环了太多次。代替此输出:

JohnSmith123 is not a member of Faker1
JohnSmith123 is not a member of Faker2
JohnSmith123 is a member of MML User

我得到以下输出:

JohnSmith123 is not a member of Faker1
JohnSmith123 is not a member of Faker2
JohnSmith123 is not a member of MML User
JohnSmith123 is not a member of Faker1
JohnSmith123 is not a member of Faker2
JohnSmith123 is not a member of MML User
JohnSmith123 is not a member of Faker1
JohnSmith123 is not a member of Faker2
JohnSmith123 is a member of MML User

我想切断它,以便它不会重复多次,但是我不确定问题出在哪里。

0 个答案:

没有答案