1

I am trying to write a python-3 based program that could refresh the members of an active directory group in a daily basis or so. The problem is, I have:

Security group : cn=groupName, ou=Groups, ou=department, dc=some, dc=company,dc=com
User group: ou=Users, ou=department, dc=some, dc=company, dc=com

The membership of user into the group can expire based on certain criteria. So, I have to

  1. Remove all the members from the group first on a daily basis
  2. Check every user in User group based on a criteria and add as member of the group if the criteria is met.

I went through ldap3 tutorial but could not find anything relevant to member add/remove.

Can you please advice me any python library that I can use or a code example would be of great help.

victor
  • 1,573
  • 11
  • 23
user1816574
  • 49
  • 1
  • 1
  • 10

2 Answers2

4

You need to enable LDAP on your Active Directory server.

Then you should be able to use ldap3 with Python to do what you want, no problem.

Have a look at ldap3.Connection.extend.microsoft in there you'll find two methods: add_members_to_groups() and remove_members_from_groups().

Their usage is documented here.

Something to get you started:

import ldap3

server = ldap3.Server('ldap.example.com')
conn = ldap3.Connection(server, user='user', password='password', auto_bind=True)

conn.add('cn=jsmith,cn=Users,dc=example,dc=com', 'user', {'sAMAccountName': 'jsmith', 'userPrincipalName': 'jsmith', 'givenName': 'John', 'sn': 'Smith'})
conn.extend.microsoft.add_members_to_groups('cn=jsmith,cn=Users,dc=example,dc=com', 'cn=My Group,cn=Users,dc=example,dc=com')

conn.unbind()

All that does is create a user and add it to a group.

Jamie Scott
  • 452
  • 4
  • 20
0

I was able to successfully add users to an AD Group using the Pyad library. The full documentation can be found here. Below is an example of adding a list of users to an AD Group.

from pyad import aduser
from pyad import adgroup

## Set AD Group Values (values derived from CN or Common Name of the AD Group)
test_group = "xxxxx-YYYYY-TEST-ZZZZ"

## Create List of Code IDs to be added
code_list = ["123456", "234567", "345678"]

## Add Users to TEST AD Group using the Pyad library
for user in code_list:  
    users = aduser.ADUser.from_cn(user)
    test_group = adgroup.ADGroup.from_cn(test_group)
    test_group.add_members(users)
Mark
  • 177
  • 3
  • 12