2

如何将 python-ldap 返回的二进制 ldap 属性转换为漂亮的十六进制表示形式,然后再次返回以在 ldap 过滤器中使用?

4

4 回答 4

4

对于与十六进制字符串相互转换的任务,您应该考虑内置 uuid 模块

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'
于 2015-03-29T02:16:22.797 回答
2
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)
于 2014-08-14T04:28:10.300 回答
1

我们可以使用 python uuid 来获取十六进制表示

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 中的原始 objectGUID 或 python UUID 对象的 guid.bytes 创建,两者都是相同的。

例子 :

search_filter = ('(objectGUID=%s)' % object_guid_from_ldap_ad)

或者

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

然后在 LDAP 搜索中使用 search_filter。

于 2018-03-15T13:34:15.767 回答
1

我无法直接使用上述任何代码来将字符串 objectGUID 表示形式转换为适用于 ldap 查询的东西。但是继续@Rel 的代码和@hernan 的评论,我能够弄清楚如何去做。我发布这个以防像我这样的人仍然对如何使用上面的细节来制定搜索过滤器感到困惑。这是我所做的:

从字符串 objectGuid 开始(我已经借用了上面的那个),我删除了连字符。

guidString = '496772af-6219-4d45-b250-3963fba0e277'.replace("-","")

您需要以字符对的形式对前三个分组的字符重新排序。我生成的订单如下:

newOrder = [6,7,4,5,2,3,0,1,10,11,8,9,14,15,12,13]       # the weird-ordered stuff
for i in range(16, len(guidString)): newOrder.append(i)  # slam the rest on

然后,我按照规定的顺序创建一个新字符串:

guid_string_in_search_order = str.join('', [guidString[i] for i in newOrder]) 
guidSearch = ''.join(['\\%s' % str.join('',guid_string_in_search_order[i:i+2]) for i in range(0, len(guid_string_in_search_order), 2)])

然后你需要在每一对前面添加转义的反斜杠:

guidSearch = ''.join(['\\%s' % str.join('',guid_string_in_search_order[i:i+2]) for i in range(0, len(guid_string_in_search_order), 2)])

这应该让您获得以下内容的 guidSearch:

'\\af\\72\\67\\49\\19\\62\\45\\4d\\b2\\50\\39\\63\\fb\\a0\\e2\\77'

因此,现在您将其设为 ldap 搜索字符串:

search_filter = '(objectGUID={})'.format(guidSearch)

就这样 - 准备好进行 ldap 搜索了。我怀疑有更多里程的人可以用更少的步骤来做这些事情,但至少这样你就可以按照我的做法去做。

于 2020-05-24T03:26:33.727 回答