Python-LDAP将objectGUID转换为十六进制字符串和b

2024-05-16 18:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将pythonldap返回的二进制ldap属性转换成一个漂亮的十六进制表示,然后再转换回ldap过滤器中使用?在


Tags: 过滤器属性二进制ldappythonldap
3条回答
def guid2hexstring(val):
    s = ['\\%02X' % ord(x) for x in val]
    return ''.join(s)

guid = ldapobject.get('objectGUID', [''])[0] # 'Igr\xafb\x19ME\xb2P9c\xfb\xa0\xe2w'
guid2string(guid).replace("\\", "") # '496772AF62194D45B2503963FBA0E277'

#and back to a value you can use in an ldap search filter

guid = ''.join(['\\%s' % guid[i:i+2] for i in range(0, len(guid), 2)]) # '\\49\\67\\72\\AF\\62\\19\\4D\\45\\B2\\50\\39\\63\\FB\\A0\\E2\\77'

searchfilter = ('(objectGUID=%s)' % guid)

我们可以使用pythonuuid来获得十六进制表示

import uuid

object_guid_from_ldap_ad = '\x1dC\xce\x04\x88h\xffL\x8bX|\xe5!,\x9b\xa9'

guid = uuid.UUID(bytes=object_guid_from_ldap_ad)
# To hex
guid.hex
# To human readable
str(guid)
# Back to bytes
assert guid.bytes == object_guid_from_ldap_ad

问题第二部分的答案。。。在

可以使用LDAP/AD或guid.字节对于pythonuuid对象,两者都是相同的。在

示例:

^{pr2}$

或者

search_filter = ('(objectGUID=%s)' % guid.bytes)

然后在LDAP搜索中使用search_过滤器。在

对于转换为和从十六进制字符串转换的任务,您应该考虑builtin uuid module。在

import uuid


object_guid = 'Igr\xafb\x19ME\xb2P9c\xfb\xa0\xe2w'
guid = uuid.UUID(bytes=object_guid)

# to hex
assert guid.hex == '496772af62194d45b2503963fba0e277'

# to human-readable guid
assert str(guid) == '496772af-6219-4d45-b250-3963fba0e277'

# to bytes
assert guid.bytes == object_guid == 'Igr\xafb\x19ME\xb2P9c\xfb\xa0\xe2w'

相关问题 更多 >