title: Get nested LDAP group members with python-ldap
body: <p>I'm trying to find the best way to get a list of all LDAP user accounts that belong to groups which are members of a groupOfNames using python-ldap.  This is on an OpenLDAP server, not AD.  I wrote the function below, which does the job but takes forever to run.  I'm hoping either python-ldap has some builtin function that I'm not aware of, or there's something I can modify to make this run more quickly.  If not, hopefully someone else will find this code useful.  Thanks in advance for any help!</p>
  
  <pre><code>def get_nested_members(con, dn):
      """
      Parameters
      ----------
      con : LDAPObject
          An authenticated python-ldap connection object
      dn : string
          The dn of the groupOfNames to be checked
  
      Returns
      -------
      members : list
          A list of all accounts that are members of the given dn
      """
  
      members = []
      searched = []
      to_search = [dn]
  
      while len(to_search) &gt; 0:
          current_dn = to_search.pop()
          cn = current_dn.split(',')[0]
          r = con.search_s(base_dn, ldap.SCOPE_SUBTREE, cn, [])[0][1]
          if 'groupOfNames' in r['objectClass']:
              if 'member' in r:
                  for i in r['member']:
                      if((i != current_dn) and (i not in searched)):
                          to_search.append(i)
              searched.append(current_dn)
          elif 'posixGroup' in r['objectClass']:
              if 'memberUid' in r:
                  for i in r['memberUid']:
                      members.append(i)
              searched.append(current_dn)
          elif 'posixAccount' in r['objectClass']:
              if 'uid' in r:
                  members.append(r['uid'][0])
          else:
              print('ERROR: encountered record of unknown type:')
              pprint(str([current_dn, r]))
      return list(set(members))
  </code></pre>