使用 Python 脚本管理远程 LDAP 服务器

Use Python script to manage remote LDAP server

背景: 我正在开发 API 来集中用户创建和管理多个资源(例如 Google Apps、Dropbox 等)。 在 Linux VM 上,我开发了一个 API 和 Web 界面,允许我(和我的共同管理员)验证和管理这些服务的用户帐户。 接下来我需要集成的是我们的 Active Directory,它托管在远程 Windows Server 2008 上。

我一直在尝试使用 python-ldap 连接到 retrieve/modify 信息,但遇到 DIR_ERROR 操作错误(尝试查询用户时)和 NAMING_VIOLATION 错误(尝试添加用户时)。

*代码基于 http://www.grotan.com/ldap/python-ldap-samples.html、Whosebug 问题和 python-ldap 文档 我认为有效的绑定代码:

import ldap
try:
    l = ldap.open("serverip")
    l.protocol_version = ldap.VERSION3  

    username = "myUserName@adtest.local"
    password  = "secret"

    result = l.simple_bind(username, password)
    print result

except ldap.LDAPError, e:
    print e

打印: (97, [], 1, [])

查询用户脚本: (按照文章的建议尝试不绑定,但收到 "In order to perform this operation a successful bind must be completed on the connection.")

import ldap

try:
    l = ldap.open("serverIp", port=389)
    l.protocol_version = ldap.VERSION3  
    username = "myUserName@adtest.local"
    password  = "secret"

    result = l.simple_bind(username, password)
    print result
except ldap.LDAPError, e:
    print e
    # handle error however you like

baseDN = "ou=Users, o=adtest.local"
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = None 
searchFilter = "cn=*myUserName*"

try:
    ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
    result_set = []
    while 1:
        result_type, result_data = l.result(ldap_result_id, 0)
        if (result_data == []):
            break
        else:
            if result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)
    print result_set
except ldap.LDAPError, e:
    print e

结果如下: (97, [], 1, []) {'info': '000020D6: SvcErr: DSID-031007DB, 问题 5012 (DIR_ERROR), 数据 0\n','desc':'Operations error'}

添加用户脚本:(使用 ldaps)

import ldap
import ldap.modlist as modlist

# Open a connection
l = ldap.initialize("ldaps://serverIp:636/")

# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("myUserName@adtest.local","secret")

# The dn of our new entry/object
dn="cn=test,dc=adtest,dc=local" 

# A dict to help build the "body" of the object
attrs = {}
attrs['objectclass'] = ['top','organizationalRole','simpleSecurityObject']
attrs['cn'] = 'test'
attrs['userPassword'] = 'aDifferentSecret'
attrs['description'] = 'test user'

# Convert our dict to nice syntax for the add-function using modlist-module
ldif = modlist.addModlist(attrs)

# Do the add-operation to the ldapserver
l.add_s(dn,ldif)

# Disconnect and free resources when done
l.unbind_s()

结果是: ldap.SERVER_DOWN:{'info':'A TLS packet with unexpected length was received.','desc':"Can't contact LDAP server"}

*这让我觉得可能是端口问题,所以我将初始化行更改为 l = ldap.initialize("ldap://serverIp:389/"),类似于其他两个脚本。

现在我得到: ldap.NAMING_VIOLATION: {'info': "00002099: NameErr: DSID-0305109C, 问题 2005 (NAMING_VIOLATION), 数据 0, 最佳匹配:\n\t'dc=adtest, dc =local'\n", 'desc': 'Naming violation'}

此外,我在 attrs 中添加了 ou 和 uid,但错误没有改变。

我做错了什么或者我可以尝试做些什么不同的事情? 感谢任何 help/suggestions!

编辑:我检查了我的服务器,端口 636 被正确设置为允许安全 LDAP 流量,所以我不知道为什么这给我的错误与普通 LDAP 不同。 edit2:我尝试在添加脚本中更改以下行 dn="cn=test,dc=adtest.local"

我的新输出(堆栈跟踪)是(我添加了 print 语句以显示绑定实际上在错误之前发生):
(97, [], 1, [])
追溯(最近一次通话最后一次):
文件 "test2.py",第 21 行,在 <module>
中 l.add_s(dn,ldif)
文件“/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,第 202 行,在 add_s
中 return self.result(msgid,all=1,timeout=self.timeout)
文件“/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,第 465 行,结果
resp_type, resp_data, resp_msgid = self.result2(msgid,all,timeout)
文件“/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,第 469 行,结果 2
resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all,timeout)
文件“/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,第 476 行,结果 3
resp_ctrl_classes=resp_ctrl_classes
文件“/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,第 483 行,结果 4
ldap_result = self._ldap_call(self._l.result4,msgid,all,timeout,add_ctrls,add_intermediates,add_extop)
文件“/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,第 106 行,在 _ldap_call
中 结果 = func(*args,**kwargs)
ldap.REFERRAL: {'info': 'Referral:\nldap://adtest.local/cn=test,dc=adtest.local', 'desc': 'Referral'}

工作查询搜索!
感谢:
http://www.linuxjournal.com/article/6988?page=0,0

import ldap

def main():

    keyword = "user_query"

    try:
        l = ldap.open(serverIp)
        l.simple_bind_s("myUserName@adtest.local", "password")
        print "successfully bound to server.\n"

        print "Searching..\n"
        my_search(l,keyword)
    except ldap.LDAPError, e:
        print "Couldn't connect. %s " % e

def my_search(l, keyword):
    #Base is for the DN(Distinguised Name) of the entry where the search should start
    base = "cn=Users,dc=adtest,dc=local"
    #Scope has three options, SUBTREE searches all sub-folder/directories
    scope = ldap.SCOPE_SUBTREE
    #filter consists of a cn(common name) and keyword.
    #putting asterisks around our keyword will match anything containing the string
    f = "cn=" + "*" + keyword + "*"
    #determines which attributes to return. Returns all if set to "None"
    retrieve_attributes = None

    count = 0
    result_set = []
    timeout = 0
    result = l.search_s(base, scope, f, retrieve_attributes)
    print result[0][1].keys()
    try:
        result_id = l.search(base, scope, f, retrieve_attributes)
        while 1:
            result_type, result_data = l.result(result_id, timeout)
            if(result_data == []):
                break
            else:
                if result_type == ldap.RES_SEARCH_ENTRY:
                    result_set.append(result_data)
        if len(result_set) == 0:
            print "No Results"
            return
        for i in range(len(result_set)):
            for entry in result_set[i]:
                try:
                    name = entry[1]['cn'][0]
                    count += 1
                    print str(count)+" "+name
                except:
                    pass
    except ldap.LDAPError, e:
        print e

if __name__=='__main__':
    main()

我修复了代码中的一个错误,但仍然无法设置某些属性,因为 LDAP 使用纯文本并且不允许在没有安全连接的情况下发送私人信息。 为了 add/modify 用户密码信息和 userAccountControl 标志(以启用用户),我使用端口 636 切换到 LDAPS,我通过添加 Active Directory 证书服务在服务器上启用了它(*需要您重新启动服务器) .
此外,您需要在初始化之前包含 'ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,0)' 行。

工作添加用户
感谢:
how to set lockoutTime and password of a user of Active Directory

import ldap
import ldap.modlist as modlist

ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,0)
l = ldap.initialize("ldaps://10.99.0.214:636")
l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
l.set_option(ldap.OPT_NETWORK_TIMEOUT, 10.0)
t = l.simple_bind_s("myUserName@adtest.local","password")

dn="cn=TestUser,cn=Users,dc=adtest,dc=local"

#make a unicode password to set for user
unicode_pass = unicode('\"'+"userPwd"+'\"', 'iso-8859-1')
password_value = unicode_pass.encode('utf-16-le')

#What I set for my users, you can find more by looking through a user's properties on your DC.
attrs = {}
attrs['cn'] = 'TestUser'
attrs['displayName'] = 'TestUser'
attrs['givenName'] = 'Test'
attrs['mail'] = 'testuser@company.com'
attrs['name'] = 'Test User'
attrs['objectclass'] = ['top','person','organizationalPerson','user']
attrs['sAMAccountName'] = 'testuser'
attrs['sn'] = 'User'
attrs['unicodepwd'] = password_value
attrs['userPrincipalName'] = 'testuser@adtest.local'

ldif = modlist.addModlist(attrs)

l.add_s(dn,ldif)

#Now that the user is created and has a password(needs to meet AD requirements), they can be enabled 

#For full userAccountControl flag list:
#http://support.microsoft.com/en-us/kb/305144
mod_acct = [(ldap.MOD_REPLACE, 'userAccountControl', '66048')]
try:
    l.modify_s(dn, mod_acct)
except ldap.LDAPError, e:
    print e

l.unbind_s()