Python 如何進行域賬號的校驗?當然是操作ldap.

首先需要安裝python-ldap的模組 http://www.python-ldap.org/。 在這裡用的是windows系統,當然比較容易,下載地址 http://pypi.python.org/pypi/python-ldap/

 

安裝後在python 的互動環境裡輸入import ldap 如果沒有問題就說明安裝成功了。

驗證程式:

#!usr/bin/env python
#coding: utf-8

import os
import sys
import ldap

def login_ldap(username, password):
    try:
        print("開始執行")
        Server = "ldap://127.0.0.1:8000"
        baseDN = "dc=domainname,dc=com"
        searchScope = ldap.SCOPE_SUBTREE
        # 設定過濾屬性,這裡只顯示cn=test的資訊
         searchFilter = "sAMAccountName=" + username
        # 為使用者名稱加上域名
         username = 'domainname\\' + username
        
        
        # None表示搜尋所有屬性,['cn']表示只搜尋cn屬性
         retrieveAttributes = None
    
        conn = ldap.initialize(Server)
        #非常重要
        conn.set_option(ldap.OPT_REFERRALS, 0)
        conn.protocol_version = ldap.VERSION3
        # 這裡使用者名稱是域賬號的全名例如domain/name
        print conn.simple_bind_s(username, password)
        print 'ldap connect successfully'

    
        #呼叫search方法返回結果id
        ldap_result_id = conn.search(baseDN, searchScope, searchFilter, retrieveAttributes)
        result_set = []
        print ldap_result_id

        print("****************")
        while 1:
            result_type, result_data = conn.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
        Name,Attrs = result_set[0][0]
        if hasattr(Attrs, 'has_key') and Attrs.has_key('name'):
            print("test3")
            distinguishedName = Attrs['mail'][0]
            #distinguishedName = Attrs['name'][0]
            #distinguishedName = Attrs['displayName'][0]
            #distinguishedName = Attrs['mail'][0]
            #distinguishedName = Attrs['memberOf'][0]
            #distinguishedName = Attrs['mailNickname'][0]
            #distinguishedName = Attrs['sAMAccountName'][0]
            #distinguishedName = Attrs['distinguishedName'][0]
            #distinguishedName = Attrs['title'][0]
            #distinguishedName = Attrs['department'][0]
            #distinguishedName = Attrs['manager'][0]
            print "Login Info for user : %s" % distinguishedName

            print Attrs['mail'][0]
            print Attrs['name'][0]
            print Attrs['displayName'][0]
            print Attrs['memberOf'][0]
            print Attrs['sAMAccountName'][0]
            print Attrs['title'][0]
            print Attrs['department'][0]


            
            return distinguishedName

        else:
            print("in error")
            return None
    except ldap.LDAPError, e:
        print("out error")
        print e
        return None
    
if __name__ == "__main__":
    username = "username" # ldap中使用者名稱
    password = "password" # ldap中密碼
    
    login_ldap(username, password)






    


 

參考:http://www.cnblogs.com/itech/archive/2011/02/11/1951576.html

python例項26[驗證使用者是否存在於LDAP Server]

 

需要安裝python2.x 和python-LDAP模組。

python-ldap:http://www.python-ldap.org/

python-ldap的windows版本下載:http://pypi.python.org/pypi/python-ldap/

 

python26例項程式碼:(用來驗證某使用者是否存在於LDAP Server)

python例項26[驗證使用者是否存在於LDAP Server]

 

需要安裝python2.x 和python-LDAP模組。

python-ldap:http://www.python-ldap.org/

python-ldap的windows版本下載:http://pypi.python.org/pypi/python-ldap/

 

python26例項程式碼:(用來驗證某使用者是否存在於LDAP Server)

python例項26[驗證使用者是否存在於LDAP Server]

 

需要安裝python2.x 和python-LDAP模組。

python-ldap:http://www.python-ldap.org/

python-ldap的windows版本下載:http://pypi.python.org/pypi/python-ldap/

 

python26例項程式碼:(用來驗證某使用者是否存在於LDAP Server)

import time
import ldap

'''
    Need install python-ldap module from:
      http://www.python-ldap.org/
    For windows OS, you can get the module from:
      http://pypi.python.org/pypi/python-ldap/
'''

ldapuser = "yourusername";
#ldapuser = "CN=yourusername,OU=XXX,OU=XXX,DC=XXX,DC=XXXXX,DC=com"
ldappass = "youruserpasswd";
ldappath = "ldap://yourldapserveriporname:yourldapserverport/";

baseDN = "DC=XXX,DC=XXXXX,DC=COM"

FoundResult_ServerBusy = "Server is busy"
FoundResult_NotFound = "Not Found"
FoundResult_Found = "Found"


def _validateLDAPUser(user):
    try:
        l = ldap.initialize(ldappath)
        l.protocol_version = ldap.VERSION3
        l.simple_bind(ldapuser,ldappass)

        searchScope  = ldap.SCOPE_SUBTREE
        searchFiltername = "sAMAccountName"
        retrieveAttributes = None
        searchFilter = '(' + searchFiltername + "=" + user +')'

        ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
        result_type, result_data = l.result(ldap_result_id,1)
        if(not len(result_data) == 0):
          #print result_data
          return 1, FoundResult_Found
        else:
          return 0, FoundResult_NotFound
    except ldap.LDAPError, e:
        #print e
        return 0, FoundResult_ServerBusy
    finally:
        l.unbind()
        del l

def validateLDAPUser(user, trynum = 30):
    i = 0
    isfound = 0
    foundResult = ""
    while(i < trynum):
        #print "try: " + str(i)
        isfound, foundResult = _validateLDAPUser(user)
        if(isfound):
          break
        #time.sleep(60)
        i+=1
    print "-------------------------------"
    print "user is :" + user
    print "isfound :" + str(isfound)
    print "FoundResult : " + foundResult
    return isfound, foundResult


參考:http://www.linuxforum.net/forum/gshowflat.php?Cat=&Board=python&Number=533078&page=1&view=collapsed&sb=5&o=all

用Python的python-ldap模組操作openldap目錄伺服器的示例程式碼

下面是搜尋目錄項的程式碼
#!/usr/bin/python
#-*- coding:utf-8 -*- #設定原始碼檔案編碼為utf-8

import ldap

try:
conn = ldap.open("server_name") #server_name為ldap伺服器名
conn.protocol_version = ldap.VERSION3 #設定ldap協議版本
username = "cn=admin,dc=company,dc=com" #使用者名稱
password = "123" #訪問密碼
conn.simple_bind(username,password) #連線

except ldap.LDAPError, e: #捕獲出錯資訊
print e

baseDN = "dc=employees,dc=company,dc=com" #設定目錄的搜尋路徑起點
searchScope = ldap.SCOPE_SUBTREE #設定可搜尋子路徑

retrieveAttributes = None #None表示搜尋所有屬性,['cn']表示只搜尋cn屬性
searchFilter = "cn=test" #設定過濾屬性,這裡只顯示cn=test的資訊

try:
ldap_result_id = conn.search(baseDN,searchScope,searchFilter,retrieveAttributes)
#呼叫search方法返回結果id
result_set = []
while 1:
result_type, result_data = conn.result(ldap_result_id, 0) #透過結果id返回資訊
if result_data == []:
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)

print result_set[0][0][1]['o'][0] #result_set是一個複合列表,需透過索引返回組織單元(o)資訊

except ldap.LDAPError, e:
print e

這裡採用的是非同步方式,同步方式的連線和搜尋命令後有“_s”字尾,如search_s。非同步方式需透過一個結果id來訪問目錄服務資訊。

 

 

下面是一個修改目錄資訊的示例:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import ldap

try:
conn = ldap.open("server_name")
conn.protocol_version = ldap.VERSION3
username = "cn=admin,dc=company,dc=com"
password = "123"
conn.simple_bind_s(username,password)

except ldap.LDAPError, e:
print e

try:
dn = "cn=test,dc=employees,dc=company,dc=com"
conn.modify_s(dn,[(ldap.MOD_ADD,'mail','[email protected]')]) #增加一個mail屬性
except ldap.LDAPError, e:
print e

ldap.MOD_ADD表示增加屬性,ldap.MOD_DELETE表示刪除屬性,ldap.MOD_REPLACE表示修改屬性。

 

 

下面是一個增加目錄項的示例:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import ldap,ldap.modlist #ldap.modlist是ldap的子模組,用於格式化目錄服務的資料項

try:
conn = ldap.open("server_name")
conn.protocol_version = ldap.VERSION3
username = "cn=admin,dc=company,dc=com"
password = "123"
conn.simple_bind_s(username,password)

except ldap.LDAPError, e:
print e

try:
dn = "cn=test,dc=card,dc=company,dc=com"
modlist = ldap.modlist.addModlist({ #格式化目錄項,除物件型別要求必填項外,
'cn': ['test'], #其它項可自由增減
'objectClass': ['top', 'person', 'organizationalPerson', 'inetOrgPerson'],
'o': ['\xe5\xb9\xbf\xe5\xb7\x9e'], #這些為utf-8編碼的中文
'street': ['\xe5\xb9\xbf\xe5\xb7\x9e'],
'sn': ['tester'],
'mail': ['[email protected]', '[email protected]'],
'homePhone': ['xxxxxxxx'], 'uid': ['test'] })
# print modlist #顯示格式化資料項,格式化後是一個元組列表
conn.add_s(dn,modlist) #呼叫add_s方法新增目錄項

except ldap.LDAPError, e:
print e

其實我們也可按格式化後元組列表的形式把目錄項直接寫到add_s()裡,省卻轉換的步驟。

下面是刪除目錄項的示例:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import ldap

try:
conn = ldap.open("server_name")
conn.protocol_version = ldap.VERSION3
username = "cn=admin,dc=test,dc=com"
password = "password"
conn.simple_bind_s(username,password)

except ldap.LDAPError, e:
print e

try:
dn = "cn=sale,dc=test,dc=com"
conn.delete_s(dn)

except ldap.LDAPError, e:
print e

參考:http://www.grotan.com/ldap/python-ldap-samples.html#search

python-ldap sample code

Binding to LDAP Server

Simple Authentication
import ldap
try:
	l = ldap.open("127.0.0.1")
	
	# you should  set this to ldap.VERSION2 if you're using a v2 directory
	l.protocol_version = ldap.VERSION3	
	# Pass in a valid username and password to get 
	# privileged directory access.
	# If you leave them as empty strings or pass an invalid value
	# you will still bind to the server but with limited privileges.
	
	username = "cn=Manager, o=anydomain.com"
	password  = "secret"
	
	# Any errors will throw an ldap.LDAPError exception 
	# or related exception so you can ignore the result
	l.simple_bind(username, password)
except ldap.LDAPError, e:
	print e
	# handle error however you like
	
							

Adding entries to an LDAP Directory

Synchrounous add
# import needed modules
import ldap
import ldap.modlist as modlist

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

# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("cn=manager,dc=example,dc=com","secret")

# The dn of our new entry/object
dn="cn=replica,dc=example,dc=com" 

# A dict to help build the "body" of the object
attrs = {}
attrs['objectclass'] = ['top','organizationalRole','simpleSecurityObject']
attrs['cn'] = 'replica'
attrs['userPassword'] = 'aDifferentSecret'
attrs['description'] = 'User object for replication using slurpd'

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

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

# Its nice to the server to disconnect and free resources when done
l.unbind_s()

                            

Modify entries in an LDAP Directory

Synchrounous modify
# import needed modules
import ldap
import ldap.modlist as modlist

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

# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("cn=manager,dc=example,dc=com","secret")

# The dn of our existing entry/object
dn="cn=replica,dc=example,dc=com" 

# Some place-holders for old and new values
old = {'description':'User object for replication using slurpd'}
new = {'description':'Bind object used for replication using slurpd'}

# Convert place-holders for modify-operation using modlist-module
ldif = modlist.modifyModlist(old,new)

# Do the actual modification 
l.modify_s(dn,ldif)

# Its nice to the server to disconnect and free resources when done
l.unbind_s()
                            

Deleting an entry from an LDAP Server

Synchronous Delete
import ldap

## first you must bind so we're doing a simple bind first
try:
	l = ldap.open("127.0.0.1")
	
	l.protocol_version = ldap.VERSION3	
	# Pass in a valid username and password to get 
	# privileged directory access.
	# If you leave them as empty strings or pass an invalid value
	# you will still bind to the server but with limited privileges.
	
	username = "cn=Manager, o=anydomain.com"
	password  = "secret"
	
	# Any errors will throw an ldap.LDAPError exception 
	# or related exception so you can ignore the result
	l.simple_bind(username, password)
except ldap.LDAPError, e:
	print e
	# handle error however you like


# The next lines will also need to be changed to support your requirements and directory
deleteDN = "uid=anyuserid, ou=Customers,ou=Sales,o=anydomain.com"
try:
	# you can safely ignore the results returned as an exception 
	# will be raised if the delete doesn't work.
	l.delete_s(deleteDN)
except ldap.LDAPError, e:
	print e
	## handle error however you like

 

 參考連結:

http://webservices.ctocio.com.cn/444/12159444.shtml

http://blog.csdn.net/sandayh/article/details/4525938

http://blog.csdn.net/sandayh/article/details/4525930

http://blog.sina.com.cn/s/blog_69ac00af01012e0g.html

http://hi.baidu.com/j60017268/item/e26222f9e56c0c1ae3e3bd28

http://www.ibm.com/developerworks/cn/aix/library/au-ldap_crud/

http://www.packtpub.com/article/installing-and-configuring-the-python-ldap-library-and-binding-to-an-ldap-directory

 

 

 

更多相關推薦

透過python-ldap處理ldap伺服器

最近專案中加入LDAP認證方式,那麼問題來了,在網站上建立使用者的時候,要將使用者同步到LDAP服務...

繼續閱讀

ldap auth

pythonldapauth 轉載於:https://www.cnblogs.com/nancy0517/p/5309958.html

繼續閱讀

關於單點登陸--LDAP

在公司上班,我們經常需要上各種各樣的內網系統,都是需要賬號登陸,要是每個系統都使用獨立的...

繼續閱讀

Flask ldap認證

 views/auth.py login.html 轉載於:https://my.oschina.net/sukai/blog/1839190

繼續閱讀

python對接ldap

ldap簡介:LDAP(LightDirectoryAccessPortocol),它是基於X.500標準的輕量級目錄訪問協議目...

繼續閱讀

django-simple-sso, django-auth...

一、django-simple-sso的使用1.1安裝1.2新建3個工程,工程名SSO1,SSO2,SSO3,SSO1作為sso的...

繼續閱讀

django使用LDAP驗證

1.安裝Python-LDAP(python_ldap-2.4.25-cp27-none-win_amd64.whl)pipinstallpython_ldap-2.4...

繼續閱讀

Python LDAP3 操作 LDAP 實現增...

在介紹具體實現之前先囉嗦幾句,很多運維朋友或正在使用LDAP的朋友來說,有很多場景需要對LDAP...

繼續閱讀

ubuntu安裝python-ldap模組

 模組一直很頭疼好多依賴的模組 今天安裝一個python-ldap 和ldap互動的模組首先安裝的時候會提...

繼續閱讀