Windows AD 与 Python

498 字
2 分钟
Windows AD 与 Python

Python 连接 Windows AD#

1. LDAP 协议#

那么在开始之前,需要先了解 LDAP 协议。因为 Python 的 ldap3 的包就是基于 LDAP 协议的。

LDAP 的全称是 Lightweight Directory Access Protocol,「轻量目录访问协议」。

它约定了 Client 与 Server 之间的信息交互格式、使用的端口号、认证方式等内容。而 「LDAP 协议的实现」,有着众多版本,例如微软的 Active Directory 是 LDAP 在 Windows 上的实现,AD 实现了 LDAP 所需的树形数据库、具体如何解析请求数据并到数据库查询然后返回结果等功能。再例如 OpenLDAP 是可以运行在 Linux 上的 LDAP 协议的开源实现。而我们平常说的 LDAP Server,一般指的是安装并配置了 Active Directory、OpenLDAP 这些程序的服务器。

2. 尝试首次连接吧#

那么,记得安装好包,顺带着也学了一下 .env 把凭据存在本地。

pip install ldap3
pip install dotenv

使用 dotenv 将密码存储在本地的 env 环境,配合 .gitignore 不让它 push 到 GitHub (那可真是完蛋了)。然后使用以下方法调用即可。

load_dotenv()
user = os.environ['LDAP_USER']
password = os.environ['LDAP_PASS']

env 下面就可以写:

LDAP_USER=<username>
LDAP_PASS=<password>

那么就开始首次连接吧!

from ldap3 import Server, Connection, ALL
# 绑定服务器
server = Server('ldap://192.168.254.10',get_info=ALL)
# 创建并打开链接
conn = Connection(server)
conn.open()
# 查看连接状态
print("Connect Status:", conn.closed)
print("root DSE info",)
print(server.info)
# 取消绑定(关闭连接)
conn.unbind()

3. 尝试读取 用户与计算机#

呼呼呼,既然已经成功连接到了目标 Server,那就进一步尝试读取 User 与 GPO 吧!

from ldap3 import Server, Connection, ALL, NTLM
from dotenv import load_dotenv
import os
load_dotenv()
user = os.environ['LDAP_USER']
password = os.environ['LDAP_PASS']
# 绑定服务器
server = Server('ldap://192.168.254.10',get_info=ALL)
# 创建并打开链接,使用 NTLM 协议
conn = Connection(
server,
user=user,
password=password,
authentication=NTLM,
auto_bind=True
)
# 在此连接中进行查询
conn.search(
search_base='DC=qy,DC=net',
search_filter='(objectClass=user)',
attributes=['sAMAccountName', 'displayName', 'distinguishedName', 'mail']
)
# For 循环将 conn.entires 中的对象遍历输出
for entry in conn.entries:
print(entry.distinguishedName)
print(' 登录名:', entry.sAMAccountName)
print(' 显示名:', entry.displayName)
print()

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

打赏
Windows AD 与 Python
https://springtsuki.xucjno.com/posts/springtsuki/notes/windowsad/910/
作者
SpringTsuki
发布于
2026-09-10
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
SpringTsuki
你好,我是浅月。
公告
浅月的开发小窝!欢迎你来到这里!
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
分类
标签
站点统计
文章
56
分类
9
标签
42
总字数
188,888
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.13.5
文章许可
CC BY-NC-SA 4.0

文章目录