Skip to content

Instantly share code, notes, and snippets.

@Duologic
Last active August 26, 2015 08:58
Show Gist options
  • Select an option

  • Save Duologic/a562ca20ec6ad8e47f7f to your computer and use it in GitHub Desktop.

Select an option

Save Duologic/a562ca20ec6ad8e47f7f to your computer and use it in GitHub Desktop.
This script is intended to create simple group without nested groups as some application can't handle nested groups in LDAP.
import ldap
from ldap import modlist
ldap_connection = 'ldap://<ip>:<port>'
domain = 'dc=<your domain>'
admin = 'cn=admin,%s' % domain
password = '<secret>'
simple_group = 'cn=<group that needs members>,ou=Groups,%s' % domain
top_group = 'cn=<top group>,ou=Groups,%s' % domain
# Initialize LDAP connection and Bind admin to it
conn = ldap.initialize(ldap_connection)
conn.bind_s(admin, password, ldap.AUTH_SIMPLE)
# Initialize first group and person list
groups = [top_group]
person = []
# Traverse the tree of groups and users
for group in groups:
membersof = conn.search_s(group, ldap.SCOPE_SUBTREE, attrlist=['member'])
for item in membersof:
for member in item[1]['member']:
isgroup = len(conn.search_s(member, ldap.SCOPE_BASE, 'objectClass=groupOfNames'))
isperson = len(conn.search_s(member, ldap.SCOPE_BASE, 'objectClass=person'))
if isgroup:
groups.append(member)
if isperson:
person.append(member)
# Create an LDIF object
old_attribute = conn.search_s(simple_group, ldap.SCOPE_SUBTREE, attrlist=['member'])
old = old_attribute[0][1]
new = {'member': set(person)}
ldif = modlist.modifyModlist(old,new)
# Modify the member attribute
conn.modify_s(simple_group, ldif)
# Unbind the admin
conn.unbind_s()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment