Python中如何获取AD域中所有的OU?
最近需要将组织架构和 AD 域中的 OU 绑定起来,但是只会用 Python-ldap 连接 AD 域
请教大神这该如何做到?
Python中如何获取AD域中所有的OU?
5 回复
import ldap3
def get_all_ous(server_url, bind_user, bind_password, search_base):
"""
获取AD域中所有组织单元(OUs)
参数:
server_url: LDAP服务器地址,例如 'ldap://domain.com'
bind_user: 绑定用户DN,例如 'cn=admin,dc=domain,dc=com'
bind_password: 绑定密码
search_base: 搜索基准DN,例如 'dc=domain,dc=com'
"""
try:
# 1. 建立连接
server = ldap3.Server(server_url, get_info=ldap3.ALL)
connection = ldap3.Connection(
server,
user=bind_user,
password=bind_password,
auto_bind=True
)
# 2. 搜索所有OU
# objectClass=organizationalUnit 表示组织单元
# 搜索范围:SUBTREE(整个子树)
connection.search(
search_base=search_base,
search_filter='(objectClass=organizationalUnit)',
search_scope=ldap3.SUBTREE,
attributes=['distinguishedName', 'name', 'description']
)
# 3. 提取结果
ous = []
for entry in connection.entries:
ou_info = {
'dn': str(entry.distinguishedName),
'name': str(entry.name) if entry.name else '',
'description': str(entry.description) if entry.description else ''
}
ous.append(ou_info)
# 4. 关闭连接
connection.unbind()
return ous
except Exception as e:
print(f"错误: {e}")
return []
# 使用示例
if __name__ == "__main__":
# 配置你的AD连接信息
SERVER = 'ldap://your-domain-controller.com'
BIND_USER = 'cn=admin_user,dc=yourdomain,dc=com' # 需要有读取权限的用户
BIND_PASSWORD = 'your_password'
SEARCH_BASE = 'dc=yourdomain,dc=com'
# 获取所有OU
all_ous = get_all_ous(SERVER, BIND_USER, BIND_PASSWORD, SEARCH_BASE)
# 打印结果
print(f"找到 {len(all_ous)} 个OU:")
for i, ou in enumerate(all_ous, 1):
print(f"{i}. {ou['name']}")
print(f" DN: {ou['dn']}")
if ou['description']:
print(f" 描述: {ou['description']}")
print()
关键点说明:
- 依赖安装:需要先安装
pip install ldap3 - 连接参数:
server_url: AD域控制器地址,可以是ldap://或ldaps://(加密)bind_user: 需要有读取权限的账户,格式为完整DNsearch_base: 搜索的起始位置,通常是域根
- 搜索过滤器:
(objectClass=organizationalUnit)专门匹配OU对象 - 搜索范围:
SUBTREE会搜索指定基准下的所有层级 - 返回属性:这里获取了DN、名称和描述,你可以根据需要添加其他属性
权限要求:使用的绑定账户至少需要有域中对象的读取权限。
一句话总结:用ldap3库连接AD,搜索objectClass=organizationalUnit的对象即可。
先获取所有 User,然后从每一个 User 的 DN 中查重。
谢谢,方法可行。 不过这样查询频率高了会不会加大服务器压力,该怎么解决,或者其他好的方法。
看标题,如果只是需要获取 AD 域中的所有 OU,用 PowerShell 是最快最便捷的,为啥一定要 Python?
参考 Example1,把输出格式换成本地 csv.
https://docs.microsoft.com/en-us/powershell/module/addsadministration/get-adorganizationalunit?view=win10-ps
因为我要把连接 AD 域加到 Python 项目中

