本文共 1368 字,大约阅读时间需要 4 分钟。
在Active Directory环境中,安全身份识别码(SID)是唯一标识用户的值。以下是将SID转换为用户名的完整步骤和示例代码。
首先,安装ldap3库。这是实现Active Directory操作的强大工具。
pip install ldap3
在Active Directory中,SID和DN(Distinguished Name)是等价的。SID可以通过将其转换为特定的字符串格式来得到DN。
ldap3 Server和Connection模块将被使用来实现这一点。
使用ldap3连接到你的Active Directory服务器,并提供管理员账户进行认证。
from ldap3 import Server, Connection, ALL, SUBTREEdef sid_to_username(sid): # 你的域名 domain = 'dc=example,dc=com' # LDAP服务器地址 server = Server('ldap.example.com', get_info=ALL) # 连接到服务器 conn = Connection(server, user='administrator@example.com', password='password') # 定义要搜索的DN dn = f"CN={sid},{domain}" 在连接成功后,搜索DN以获取用户的CN(Common Name)。
# 搜索所有匹配项conn.search(dn, '(objectClass=*)', search_scope=SUBTREE)if conn.entries: # 返回用户名 return conn.entries[0]['cn'][0]else: return None
def test_sid_to_username(): assert sid_to_username('S-1-5-21-123456789-987654321-000000000-1001') == 'John Doe' assert sid_to_username('S-1-5-21-234567890-098765432-000000000-2002') == 'Jane Smith' assert sid_to_username('S-1-5-21-345678901-987654321-000000000-3003') == 'Alice Johnson' 运行上述代码可以验证函数的正确性。每个SID都会返回相应的用户名,确保函数正常工作。
ldap3的日志或错误信息。通过以上步骤,你可以轻松地将SID转换为Active Directory用户名,并在代码中实现这一功能。
转载地址:http://taafk.baihongyu.com/