简体   繁体   English

在 python 中向/从活动目录组添加和删除成员

[英]adding and removing members to/from active directory group in python

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.我正在尝试编写一个基于 python-3 的程序,它可以每天左右刷新活动目录组的成员。 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.我浏览了 ldap3 教程,但找不到与成员添加/删除相关的任何内容。

Can you please advice me any python library that I can use or a code example would be of great help.你能告诉我任何我可以使用的 python 库吗?或者代码示例会有很大帮助。

You need to enable LDAP on your Active Directory server.您需要在 Active Directory 服务器上启用 LDAP。

Then you should be able to use ldap3 with Python to do what you want, no problem.然后你应该能够使用ldap3和 Python 来做你想做的事,没问题。

Have a look at ldap3.Connection.extend.microsoft in there you'll find two methods: add_members_to_groups() and remove_members_from_groups() .看看其中的ldap3.Connection.extend.microsoft ,您会发现两种方法: add_members_to_groups()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.所做的只是创建一个用户并将其添加到一个组中。

I was able to successfully add users to an AD Group using the Pyad library.我能够使用 Pyad 库成功地将用户添加到 AD 组。 The full documentation can be found here .可以在此处找到完整的文档。 Below is an example of adding a list of users to an AD Group.下面是将用户列表添加到 AD 组的示例。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM