博客
关于我
Python ldap3 代码从 SID 获取用户名
阅读量:800 次
发布时间:2023-03-05

本文共 1368 字,大约阅读时间需要 4 分钟。

如何将SID转换为Active Directory用户名

在Active Directory环境中,安全身份识别码(SID)是唯一标识用户的值。以下是将SID转换为用户名的完整步骤和示例代码。

安装所需库

首先,安装ldap3库。这是实现Active Directory操作的强大工具。

pip install ldap3

将SID转换为DN

在Active Directory中,SID和DN(Distinguished Name)是等价的。SID可以通过将其转换为特定的字符串格式来得到DN。

ldap3 Server和Connection模块将被使用来实现这一点。

使用LDAP查询获取用户名

步骤一:配置LDAP连接

使用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都会返回相应的用户名,确保函数正常工作。

注意事项

  • 确保域名正确无误。
  • 检查LDAP服务器地址是否正确。
  • 确保管理员账户权限足够。
  • 如果遇到问题,可以查看ldap3的日志或错误信息。

通过以上步骤,你可以轻松地将SID转换为Active Directory用户名,并在代码中实现这一功能。

转载地址:http://taafk.baihongyu.com/

你可能感兴趣的文章
python | bleach,一个超强的 Python 库!
查看>>
python | cartopy,一个有趣的 Python 库!
查看>>
python | cloud-init,一个实用的 云计算 Python 库!
查看>>
python | code2flow,一个神奇的 Python 库!
查看>>
python | cudf,一个超实用的 Python 库!
查看>>
python | daphne,一个非常nice的 Python 库!
查看>>
python调用halcon
查看>>
python | doit,一个非常实用的 Python 库!
查看>>
python | easyocr,一个超厉害的 关于OCR的 Python 库!
查看>>
python | fastFM,一个高级的 Python 库!
查看>>
python | feature_engine,一个实用的 Python 库!
查看>>
python | filelock,一个超酷的 Python 库!
查看>>
python | fire,一个强大的 Python 库!
查看>>
python | flanker,一个神奇的 Python 库!
查看>>
python | flower,一个强大的 Python 库!
查看>>
python | funcy,一个超强的 提供函数式编程工具 Python 库!
查看>>
python | ggplot,一个超强的 Python 库!
查看>>
python | grab,一个强大的 Python 库!
查看>>
python | gunicorn,一个非常实用的 Python 库!
查看>>
python | h5py,一个无敌的关于 HDF5 的 Python 库!
查看>>