博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python+ldap实例
阅读量:4054 次
发布时间:2019-05-25

本文共 12404 字,大约阅读时间需要 41 分钟。

Python 如何进行域账号的校验?当然是操作ldap.

首先需要安装python-ldap的模块 。 在这里用的是windows系统,当然比较容易,下载地址 。

 

安装后在python 的交互环境里输入import ldap 如果没有问题就说明安装成功了。

验证程序:

#!usr/bin/env python#coding: utf-8import osimport sysimport ldapdef 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)

 

参考:

 

需要安装python2.x 和python-LDAP模块。

python-ldap:

python-ldap的windows版本下载:

 

python26实例代码:(用来验证某用户是否存在于LDAP Server)

 

需要安装python2.x 和python-LDAP模块。

python-ldap:

python-ldap的windows版本下载:

 

python26实例代码:(用来验证某用户是否存在于LDAP Server)

 

需要安装python2.x 和python-LDAP模块。

python-ldap:

python-ldap的windows版本下载:

 

python26实例代码:(用来验证某用户是否存在于LDAP Server)

import timeimport 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 ldef 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

参考:

用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','test@163.com')]) #增加一个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': ['test@163.com', 'test@21cn.com'],
'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

参考:

python-ldap sample code

Binding to LDAP Server

Simple Authentication
import ldaptry:	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 modulesimport ldapimport ldap.modlist as modlist# Open a connectionl = ldap.initialize("ldaps://localhost.localdomain:636/")# Bind/authenticate with a user with apropriate rights to add objectsl.simple_bind_s("cn=manager,dc=example,dc=com","secret")# The dn of our new entry/objectdn="cn=replica,dc=example,dc=com" # A dict to help build the "body" of the objectattrs = {}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-moduleldif = modlist.addModlist(attrs)# Do the actual synchronous add-operation to the ldapserverl.add_s(dn,ldif)# Its nice to the server to disconnect and free resources when donel.unbind_s()

Modify entries in an LDAP Directory

Synchrounous modify
# import needed modulesimport ldapimport ldap.modlist as modlist# Open a connectionl = ldap.initialize("ldaps://localhost.localdomain:636/")# Bind/authenticate with a user with apropriate rights to add objectsl.simple_bind_s("cn=manager,dc=example,dc=com","secret")# The dn of our existing entry/objectdn="cn=replica,dc=example,dc=com" # Some place-holders for old and new valuesold = {'description':'User object for replication using slurpd'}new = {'description':'Bind object used for replication using slurpd'}# Convert place-holders for modify-operation using modlist-moduleldif = modlist.modifyModlist(old,new)# Do the actual modification l.modify_s(dn,ldif)# Its nice to the server to disconnect and free resources when donel.unbind_s()

Deleting an entry from an LDAP Server

Synchronous Delete
import ldap## first you must bind so we're doing a simple bind firsttry:	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 directorydeleteDN = "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://fkxci.baihongyu.com/

你可能感兴趣的文章
uboot start.s文件分析
查看>>
没有路由器的情况下,开发板,虚拟机Ubuntu,win10主机,三者也可以ping通
查看>>
本地服务方式搭建etcd集群
查看>>
安装k8s Master高可用集群
查看>>
忽略图片透明区域的事件(Flex)
查看>>
忽略图片透明区域的事件(Flex)
查看>>
AS3 Flex基础知识100条
查看>>
Flex动态获取flash资源库文件
查看>>
01Java基础语法-16. while循环结构
查看>>
01Java基础语法-19. 循环跳转控制语句
查看>>
Django框架全面讲解 -- Form
查看>>
今日互联网关注(写在清明节后):每天都有值得关注的大变化
查看>>
”舍得“大法:把自己的优点当缺点倒出去
查看>>
[今日关注]鼓吹“互联网泡沫,到底为了什么”
查看>>
[互联网学习]如何提高网站的GooglePR值
查看>>
[关注大学生]求职不可不知——怎样的大学生不受欢迎
查看>>
[关注大学生]读“贫困大学生的自白”
查看>>
[互联网关注]李开复教大学生回答如何学好编程
查看>>
[关注大学生]李开复给中国计算机系大学生的7点建议
查看>>
[茶余饭后]10大毕业生必听得歌曲
查看>>