使用Python脚本来管理远程LDAP服务器(Use Python script to manage

2019-10-22 11:15发布

背景:我正在一个API来集中用户对多个资源(例如谷歌企业应用套件,Dropbox的,等等)的创建和管理。 在Linux虚拟机,我开发了一个API和Web界面,让我(和我的合作管理员)来验证和管理这些服务的用户帐户。 我需要整合的下一件事是我们这是一个远程的Windows Server 2008上承载的Active Directory。

我一直在尝试使用Python-LDAP连接并检索/修改信息,但(当试图查询用户)和NAMING_VIOLATION错误(尝试添加用户时)曾与DIR_ERROR操作错误问题。

*代码基于http://www.grotan.com/ldap/python-ldap-samples.html ,计算器问题,和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,[])

(试过没有绑定文章的建议,但收到“为了执行这个操作成功绑定必须在连接上完成。”):用于用户脚本查询

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,[]){ '信息': '000020D6:SvcErr:DSID-031007DB,问题5012(DIR_ERROR),数据0 \ n', '降序':'操作错误“}

添加用户脚本:(使用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:{“信息”:“突发长度为TLS接收数据包。”,“倒序”:“无法联系LDAP服务器”}

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

现在,我得到:ldap.NAMING_VIOLATION:{ '信息':“00002099:NameErr:DSID-0305109C,2005年问题(NAMING_VIOLATION),数据0的最佳匹配:\ n \ t'dc = ADTEST,DC =本地'\ n ”,‘说明’:‘命名冲突’}

此外,我与添加OU和UID到ATTRS但错误没有变化搞砸周围。

我究竟做错了还是什么我能尝试做不同? 谢谢你的任何帮助/建议!

编辑:我检查了我的服务器,端口636被正确地设置为允许安全LDAP流量,所以我不知道为什么,这是给我不同的错误比正常的LDAP。 EDIT2:我试图改变下面一行在我添加脚本DN =“CN =测试,DC = adtest.local”

并且新的输出(堆栈跟踪)我是(我增加了打印语句表明绑定实际发生现在的错误之前):
(97,[],1,[])
回溯(最近通话最后一个):
文件“test2.py”,第21行,在<module>
l.add_s(DN,LDIF)
文件 “/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,线路202,在add_s
返回self.result(MSGID,所有= 1,超时= self.timeout)
文件“/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,线路465,在结果
resp_type,resp_data,resp_msgid = self.result2(MSGID,全部,超时)
文件 “/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,线路469,在RESULT2
resp_type,resp_data,resp_msgid,resp_ctrls = self.result3(MSGID,全部,超时)
文件 “/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,线路476,在result3
resp_ctrl_classes = resp_ctrl_classes
文件 “/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,线路483,在result4
ldap_result = self._ldap_call(self._l.result4,MSGID,所有,超时add_ctrls,add_intermediates,add_extop)
文件 “/usr/local/lib/python2.7/dist-packages/ldap/ldapobject.py”,线106,在_ldap_call
结果= FUNC(*指定参数时,** kwargs)
ldap.REFERRAL:{ '信息': '推荐:\ NLDAP://adtest.local/cn=test,dc=adtest.local', '递减': '推荐'}

Answer 1:

工作查询搜索!
归功于:
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使用纯文本,不允许私人信息到没有安全连接来发送依然无法设置某些属性。 为了添加/修改用户密码信息和UserAccountControl标志(以使用户),我切换到使用端口636 LDAPS,这是我在服务器上启用加入Active Directory证书服务(*要求您重新启动服务器)。
另外,您还需要包括“ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,0)”行,你初始化之前。

工作添加用户
归功于:
如何设置lockoutTime和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()


文章来源: Use Python script to manage remote LDAP server