python 3.7 and ldap3 reading group membership












1















I am using Python 3.7 and ldap3. I can make a connection and retrieve a list of the groups in which I am interested. I am having trouble getting group members though.



server = Server('ldaps.ad.company.com', use_ssl=True, get_info=ALL)
with Connection(server, 'mydomain\ldapUser', '******', auto_bind=True) as conn:

base = "OU=AccountGroups,OU=UsersAndGroups,OU=WidgetDepartment,"
+ "OU=LocalLocation,DC=ad,DC=company,DC=com"

criteria = """(
&(objectClass=group)
(
|(sAMAccountName=grp-*widgets*)
(sAMAccountName=grp-oldWidgets)
)
)"""

attributes = ['sAMAccountName', 'distinguishedName']
conn.search(base, criteria, attributes=attributes)
groups = conn.entries


At this point groups contains all the groups I want. I want to itterate over the groups to collect the members.



    for group in groups:
# print(cn)

criteria = f"""
(&
(objectClass=person)
(memberof:1.2.840.113556.1.4.1941:={group.distinguishedName})
)
"""
# criteria = f"""
# (&
# (objectClass=person)
# (memberof={group.distinguishedName})
# )
# """

attributes = ['displayName', 'sAMAccountName', 'mail']
conn.search(base, criteria, attributes=attributes)
people = conn.entries


I know there are people in the groups but people is always an empty list. It doesn't matter if I do a recirsive search or not.



What am I missing?



Edit



There is a longer backstory to this question that is too long to go into. I have a theory about this particular issue though. I was running out of time and switched to a different python LDAP library -- which is working. I think the issue with this question might be that I "formated" the query over multiple lines. The new ldap lib (python-ldap) complained and I stripped out the newlines and it just worked. I have not had time to go back and test that theory with ldap3.










share|improve this question





























    1















    I am using Python 3.7 and ldap3. I can make a connection and retrieve a list of the groups in which I am interested. I am having trouble getting group members though.



    server = Server('ldaps.ad.company.com', use_ssl=True, get_info=ALL)
    with Connection(server, 'mydomain\ldapUser', '******', auto_bind=True) as conn:

    base = "OU=AccountGroups,OU=UsersAndGroups,OU=WidgetDepartment,"
    + "OU=LocalLocation,DC=ad,DC=company,DC=com"

    criteria = """(
    &(objectClass=group)
    (
    |(sAMAccountName=grp-*widgets*)
    (sAMAccountName=grp-oldWidgets)
    )
    )"""

    attributes = ['sAMAccountName', 'distinguishedName']
    conn.search(base, criteria, attributes=attributes)
    groups = conn.entries


    At this point groups contains all the groups I want. I want to itterate over the groups to collect the members.



        for group in groups:
    # print(cn)

    criteria = f"""
    (&
    (objectClass=person)
    (memberof:1.2.840.113556.1.4.1941:={group.distinguishedName})
    )
    """
    # criteria = f"""
    # (&
    # (objectClass=person)
    # (memberof={group.distinguishedName})
    # )
    # """

    attributes = ['displayName', 'sAMAccountName', 'mail']
    conn.search(base, criteria, attributes=attributes)
    people = conn.entries


    I know there are people in the groups but people is always an empty list. It doesn't matter if I do a recirsive search or not.



    What am I missing?



    Edit



    There is a longer backstory to this question that is too long to go into. I have a theory about this particular issue though. I was running out of time and switched to a different python LDAP library -- which is working. I think the issue with this question might be that I "formated" the query over multiple lines. The new ldap lib (python-ldap) complained and I stripped out the newlines and it just worked. I have not had time to go back and test that theory with ldap3.










    share|improve this question



























      1












      1








      1








      I am using Python 3.7 and ldap3. I can make a connection and retrieve a list of the groups in which I am interested. I am having trouble getting group members though.



      server = Server('ldaps.ad.company.com', use_ssl=True, get_info=ALL)
      with Connection(server, 'mydomain\ldapUser', '******', auto_bind=True) as conn:

      base = "OU=AccountGroups,OU=UsersAndGroups,OU=WidgetDepartment,"
      + "OU=LocalLocation,DC=ad,DC=company,DC=com"

      criteria = """(
      &(objectClass=group)
      (
      |(sAMAccountName=grp-*widgets*)
      (sAMAccountName=grp-oldWidgets)
      )
      )"""

      attributes = ['sAMAccountName', 'distinguishedName']
      conn.search(base, criteria, attributes=attributes)
      groups = conn.entries


      At this point groups contains all the groups I want. I want to itterate over the groups to collect the members.



          for group in groups:
      # print(cn)

      criteria = f"""
      (&
      (objectClass=person)
      (memberof:1.2.840.113556.1.4.1941:={group.distinguishedName})
      )
      """
      # criteria = f"""
      # (&
      # (objectClass=person)
      # (memberof={group.distinguishedName})
      # )
      # """

      attributes = ['displayName', 'sAMAccountName', 'mail']
      conn.search(base, criteria, attributes=attributes)
      people = conn.entries


      I know there are people in the groups but people is always an empty list. It doesn't matter if I do a recirsive search or not.



      What am I missing?



      Edit



      There is a longer backstory to this question that is too long to go into. I have a theory about this particular issue though. I was running out of time and switched to a different python LDAP library -- which is working. I think the issue with this question might be that I "formated" the query over multiple lines. The new ldap lib (python-ldap) complained and I stripped out the newlines and it just worked. I have not had time to go back and test that theory with ldap3.










      share|improve this question
















      I am using Python 3.7 and ldap3. I can make a connection and retrieve a list of the groups in which I am interested. I am having trouble getting group members though.



      server = Server('ldaps.ad.company.com', use_ssl=True, get_info=ALL)
      with Connection(server, 'mydomain\ldapUser', '******', auto_bind=True) as conn:

      base = "OU=AccountGroups,OU=UsersAndGroups,OU=WidgetDepartment,"
      + "OU=LocalLocation,DC=ad,DC=company,DC=com"

      criteria = """(
      &(objectClass=group)
      (
      |(sAMAccountName=grp-*widgets*)
      (sAMAccountName=grp-oldWidgets)
      )
      )"""

      attributes = ['sAMAccountName', 'distinguishedName']
      conn.search(base, criteria, attributes=attributes)
      groups = conn.entries


      At this point groups contains all the groups I want. I want to itterate over the groups to collect the members.



          for group in groups:
      # print(cn)

      criteria = f"""
      (&
      (objectClass=person)
      (memberof:1.2.840.113556.1.4.1941:={group.distinguishedName})
      )
      """
      # criteria = f"""
      # (&
      # (objectClass=person)
      # (memberof={group.distinguishedName})
      # )
      # """

      attributes = ['displayName', 'sAMAccountName', 'mail']
      conn.search(base, criteria, attributes=attributes)
      people = conn.entries


      I know there are people in the groups but people is always an empty list. It doesn't matter if I do a recirsive search or not.



      What am I missing?



      Edit



      There is a longer backstory to this question that is too long to go into. I have a theory about this particular issue though. I was running out of time and switched to a different python LDAP library -- which is working. I think the issue with this question might be that I "formated" the query over multiple lines. The new ldap lib (python-ldap) complained and I stripped out the newlines and it just worked. I have not had time to go back and test that theory with ldap3.







      python-3.7 ldap3






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 2:20







      7 Reeds

















      asked Nov 20 '18 at 16:48









      7 Reeds7 Reeds

      77211027




      77211027
























          1 Answer
          1






          active

          oldest

          votes


















          1














          people is overwritten in each iteration of your loop over groups.
          Maybe the search result for the last group entry in groups is just empty.



          You should initialise an empty list outside of your loop and extend it with your results:



          people = 
          for group in groups:
          ...
          conn.search(...)
          people.extend(conn.entries)


          Another note about your code snippet above. When combining objectClass definitions with attribute definitions in your search filter you may consider using the Reader class which will combine those internally.



          Furthermore I would like to point out that I've created an object relational mapper where you can simply define your queries using declarative python syntax, e.g.:



          from ldap3_orm import ObjectDef, Reader
          from ldap3_orm.config import config
          from ldap3_orm.connection import conn

          PersonDef = ObjectDef("person", conn)
          r = Reader(conn, PersonDef, config.base_dn, PersonDef.memberof == group.distinguishedName)
          r.search()


          ldap3-orm documentation can be found at http://code.bsm-felder.de/doc/ldap3-orm






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397738%2fpython-3-7-and-ldap3-reading-group-membership%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            people is overwritten in each iteration of your loop over groups.
            Maybe the search result for the last group entry in groups is just empty.



            You should initialise an empty list outside of your loop and extend it with your results:



            people = 
            for group in groups:
            ...
            conn.search(...)
            people.extend(conn.entries)


            Another note about your code snippet above. When combining objectClass definitions with attribute definitions in your search filter you may consider using the Reader class which will combine those internally.



            Furthermore I would like to point out that I've created an object relational mapper where you can simply define your queries using declarative python syntax, e.g.:



            from ldap3_orm import ObjectDef, Reader
            from ldap3_orm.config import config
            from ldap3_orm.connection import conn

            PersonDef = ObjectDef("person", conn)
            r = Reader(conn, PersonDef, config.base_dn, PersonDef.memberof == group.distinguishedName)
            r.search()


            ldap3-orm documentation can be found at http://code.bsm-felder.de/doc/ldap3-orm






            share|improve this answer




























              1














              people is overwritten in each iteration of your loop over groups.
              Maybe the search result for the last group entry in groups is just empty.



              You should initialise an empty list outside of your loop and extend it with your results:



              people = 
              for group in groups:
              ...
              conn.search(...)
              people.extend(conn.entries)


              Another note about your code snippet above. When combining objectClass definitions with attribute definitions in your search filter you may consider using the Reader class which will combine those internally.



              Furthermore I would like to point out that I've created an object relational mapper where you can simply define your queries using declarative python syntax, e.g.:



              from ldap3_orm import ObjectDef, Reader
              from ldap3_orm.config import config
              from ldap3_orm.connection import conn

              PersonDef = ObjectDef("person", conn)
              r = Reader(conn, PersonDef, config.base_dn, PersonDef.memberof == group.distinguishedName)
              r.search()


              ldap3-orm documentation can be found at http://code.bsm-felder.de/doc/ldap3-orm






              share|improve this answer


























                1












                1








                1







                people is overwritten in each iteration of your loop over groups.
                Maybe the search result for the last group entry in groups is just empty.



                You should initialise an empty list outside of your loop and extend it with your results:



                people = 
                for group in groups:
                ...
                conn.search(...)
                people.extend(conn.entries)


                Another note about your code snippet above. When combining objectClass definitions with attribute definitions in your search filter you may consider using the Reader class which will combine those internally.



                Furthermore I would like to point out that I've created an object relational mapper where you can simply define your queries using declarative python syntax, e.g.:



                from ldap3_orm import ObjectDef, Reader
                from ldap3_orm.config import config
                from ldap3_orm.connection import conn

                PersonDef = ObjectDef("person", conn)
                r = Reader(conn, PersonDef, config.base_dn, PersonDef.memberof == group.distinguishedName)
                r.search()


                ldap3-orm documentation can be found at http://code.bsm-felder.de/doc/ldap3-orm






                share|improve this answer













                people is overwritten in each iteration of your loop over groups.
                Maybe the search result for the last group entry in groups is just empty.



                You should initialise an empty list outside of your loop and extend it with your results:



                people = 
                for group in groups:
                ...
                conn.search(...)
                people.extend(conn.entries)


                Another note about your code snippet above. When combining objectClass definitions with attribute definitions in your search filter you may consider using the Reader class which will combine those internally.



                Furthermore I would like to point out that I've created an object relational mapper where you can simply define your queries using declarative python syntax, e.g.:



                from ldap3_orm import ObjectDef, Reader
                from ldap3_orm.config import config
                from ldap3_orm.connection import conn

                PersonDef = ObjectDef("person", conn)
                r = Reader(conn, PersonDef, config.base_dn, PersonDef.memberof == group.distinguishedName)
                r.search()


                ldap3-orm documentation can be found at http://code.bsm-felder.de/doc/ldap3-orm







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 3 '18 at 22:17









                cfeldercfelder

                112




                112






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397738%2fpython-3-7-and-ldap3-reading-group-membership%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    'app-layout' is not a known element: how to share Component with different Modules

                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                    WPF add header to Image with URL pettitions [duplicate]