簡體   English   中英

使用 Python-LDAP 查找最大 UID

[英]Find Max UID using Python-LDAP

我正在嘗試使用 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.htmlhttp://www.perlmonks.org/?node_id=457108 的帖子,它們與我的問題非常相似

有人可以幫我找到最大的 UID 以便我可以解決這個問題。

試圖解決類似的問題,我認為這有助於獲取下一個可用的 uidNumber:

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

如果您使用支持服務器端排序的 LDAP 服務器(請參閱RFC 2891 ),例如帶有slapo-sssvlv 的OpenLDAP,您可以通過以相反的排序順序准確搜索一個搜索結果來搜索最高數字。

基於python-ldap 的Python 片段(摘自Æ-DIR 的CLI 工具之一):

import ldap
from ldap.controls.sss import SSSRequestControl

def highest_id(ldap_conn, searchbase, 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 的覆蓋slapo-unique 這避免了並發客戶端添加新條目時的重復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM