使用PythonLDAP查找Max UID

2024-04-25 16:44:32 发布

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

我尝试使用python模块在LDAP条目中查找/搜索最大UID值。我的代码看起来像这样

def search_max_uid():
    filter_uid = 'uid=*'
    attributes = ['uidNumber']
    resulting = l.search_ext(base_dn,ldap.SCOPE_SUBTREE,filter_uid,attributes)
    print resulting

一旦我从整个服务器获得最大UID,我就可以+1并向组中添加一个新用户。我看到了一些类似于http://www.openldap.org/lists/openldap-software/200110/msg00539.html和{a2}的帖子,它们与我的问题非常相似

有人能帮我找到最大UID以便我能解决这个问题。在


Tags: 模块代码searchuiddef条目filterldap
2条回答

如果您使用支持服务器端排序的LDAP服务器(请参见RFC 2891),就像OpenLDAP with slapo-sssvlv,那么您可以通过按相反的排序顺序只搜索一个搜索结果来搜索最高的数字。在

基于python-ldap的Python代码段(摘录自Æ-DIR'sCLI工具之一):

import ldap
from ldap.controls.sss import SSSRequestControl

def highest_id(ldap_conn, id_attr):
    """
    search the highest value of `id_attr' by using server-side (reverse) sorting
    """
    # reverse sorting request control
    sss_control = SSSRequestControl(criticality=True, ordering_rules=['-'+id_attr])
    # send search request
    msg_id = ldap_conn.search(
        searchbase,
        ldap.SCOPE_SUBTREE,
        '({0}=*)'.format(id_attr),
        attrlist=[id_attr],
        sizelimit=1,
        serverctrls=[sss_control],
    )
    # collect result
    ldap_result = []
    try:
        for _, res_data, _, res_controls in ldap_conn.results(
                msg_id,
                add_ctrls=0
            ):
            ldap_result.extend(res_data)
    except ldap.SIZELIMIT_EXCEEDED:
        pass

    if not ldap_result:
        logging.error('No entry with attribute %r found!', id_attr)
        raise ValueError('No LDAP result!')

    highest_id_number = int(ldap_result[0][1][id_attr][0])
    logging.debug('Highest %r value found: %d', id_attr, highest_id_number)
    return highest_id_number

请注意,在分配新的ID时,这并不总是您想要的,因为ID编号空间中的间隙不会被(重复)使用。在

还要确保使用服务器端唯一的约束插件,例如OpenLDAP的overlayslapo-unique。这避免了并发客户端添加新条目时的重复。在

尝试解决类似的问题,我认为这在获得下一个可用UID编号时有效:

import ldap

l = ldap.initialize("ldap://localhost")
l.simple_bind_s("cn=blah,dc=blah,dc=blah", supersecretpassword)
res = l.search_s("dc=blah,dc=blah", ldap.SCOPE_SUBTREE, 'objectclass=posixaccount', ['uidNumber'])
uidNum = 0

for a in res:
    uidNumtemp = a[1].get('uidNumber')[0]
    if uidNumtemp > uidNum:
       uidNum = uidNumtemp
print "Highest:", uidNum
nextNum = int(uidNum) + 1
print "next uidNumber:", nextNum

相关问题 更多 >

    热门问题