可以将返回的属性强制为小写吗

Can returned attributes be forced into lowercase

我们的 LDAP 服务器上的更改改变了从搜索返回的属性的大小写。例如,“mailroutingaddress”现在是“mailRoutingAddress”。搜索本身不区分大小写,但是 python 处理返回的 ldap 对象的代码试图引用所有小写的属性并失败。

有没有一种简单的方法可以指定 LDAP 模块应该将所有返回的属性小写?或者,是否有一种直接的方法可以在返回结果后立即将它们更改为小写?

我们正在努力避免大量重写来处理我们 LDAP 软件中的这一变化。

此代码 returns 错误“找不到密钥”

timestamp_filter = ldap.filter.filter_format("a filter that works as intended")
timestamp_result = search_ldap(timestamp_filter, ['modifytimestamp'])
if not timestamp_result:
    log_it('WARN', 'No timestamp returned for group "%s"' % group_cn)
    return False
else:
    mod = timestamp_result[0][1]['modifytimestamp'][0].decode('utf-8').split('Z')[0]

当最后一行改成这个时,它起作用了:

    mod = timestamp_result[0][1]['modifyTimestamp'][0].decode('utf-8').split('Z')[0]

我希望在第一次绑定 ldap 对象时我能做点什么:

def bind_to_ldap(dn=auth_dn,pwd=auth_pwd):
  # create connection to ldap and pass bind object back to caller
  try:
    ldc = ldap.initialize(uri, bytes_mode=False)
    bind = ldc.simple_bind_s(dn, pwd)
  except ldap.LDAPError as lerr:
    log_it('EXCEPTION',"Exception raised when attempting to bind to LDAP server %s with dn %s" % (uri, dn))
    graceful_exit("%s" % lerr)

  return ldc

或者,我可以遍历搜索函数传回的所有属性。

s_filter = ldap.filter.filter_format("a filter that works as intended")
s_results = search_ldap(s_filter)

groups = {}
# okay, lots of processing do here....

for group in s_results:
    # etc. etc. etc.

您可以通过字典理解很容易地将字典的键更改为小写:

>>> timestamp_result = {'modifyTimestamp': 'foo'}
>>> timestamp_result = {k.lower(): v for k, v in timestamp_result.items()}
>>> timestamp_result
{'modifytimestamp': 'foo'}

更强大的解决方案是让 search_ldap 函数规范化服务器输出——这将最大限度地减少服务器响应更改时需要更新的代码量。