Search code examples
pythondnspyad

Add group membership to AD with PyAD


I've been trying to add group membership to my user in AD via PyAD.

from pyad import *
pyad.set_defaults(ldap_server="someSchool.local", username="someAdmin", password='somePassword')

user = pyad.aduser.ADUser.from_cn('Student999')
print(user.get_attribute('memberOf'))
user.update_attribute('mail','student999@someschool.com')
user.append_to_attribute('memberOf','CN=Active,OU=Groups,OU=Students,DC=someSchool,DC=local')

Everything works except append_to_attribute method. Print method correctly prints members' list added to user account. Method update_attribute correctly updates mail field. But when I run append_to_attribute and I try to add next member group to my user, it throws an exception:

(-2147352567, 'Exception occured.', (0, 'Active Directory', 'Server is unwilling to process the request\r\n', None, 0, -2147016651), None)

What am I doing wrong?


Solution

  • Ok, I solved the problem. According to this Is it possible to set a users memberOf property in Active Directory using Powershell attribute memberOf cannot be updated.

    So, this works for me:

    from pyad import *
    pyad.set_defaults(ldap_server="someSchool.local", username="someAdmin", password='somePassword')
    
    user = pyad.aduser.ADUser.from_cn('Student999')
    group = pyad.adgroup.ADGroup.from_dn("CN=Active,OU=Groups,OU=Students,DC=someSchool,DC=local")  
    user.add_to_group(group)