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 ldap3pip 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, NTLMfrom dotenv import load_dotenvimport 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/相关文章智能推荐
1
Windows AD 实训:备份与恢复
AD简单做个小小的 Backups 的恢复流程。需要详细的截图!
2
Windows AD Powershell
ADPowershell 常用指令集合!
3
Windows AD 入门
AD一些基本的 AD 知识
4
Windows AD PowerShell(八):Kerberos 与票据
AD理解 Kerberos 的 TGT、服务票据与缓存,并使用 Klist 和事件日志排查认证及权限问题。
5
Windows AD PowerShell(二):组与成员
AD使用 PowerShell 管理 Active Directory 组、成员关系与权限排查。
随机文章随机推荐













