广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python+ldap实例
  • 716
分享到

python+ldap实例

实例pythonldap 2023-01-31 06:01:27 716人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

python 如何进行域账号的校验?当然是操作ldap. 首先需要安装Python-ldap的模块 Http://www.python-ldap.org/。 在这里用的是windows系统,当然比较容易,下载地址 http://pypi.

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

 

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

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

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

 

python26实例代码:(用来验证某用户是否存在于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)

 

需要安装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','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

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

python-ldap sample code
  • Bind
  • Add
  • Modify
  • Search
  • Delete

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

 

 

 

--结束END--

本文标题: python+ldap实例

本文链接: https://www.lsjlt.com/news/190252.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python+ldap实例
    Python 如何进行域账号的校验?当然是操作ldap. 首先需要安装python-ldap的模块 http://www.python-ldap.org/。 在这里用的是windows系统,当然比较容易,下载地址 http://pypi....
    99+
    2023-01-31
    实例 python ldap
  • python 使用ldap实例
    #coding: utf-8 ldap_config = { 'ldap_path': 'ldap://xx.xx.xx.xx:389', 'base_dn': 'ou=users,dc=ledo,dc=com', 'lda...
    99+
    2023-01-31
    实例 python ldap
  • Python ldap实现登录实例代码
    下面一段代码是小编给大家介绍的Python ldap实现登录实例代码,一起看看吧 ldap_config = { 'ldap_path': 'ldap://xx.xx.xx.xx:389', '...
    99+
    2022-06-04
    实例 代码 Python
  • JAVA_基本LDAP操作实例
    一、简介 Lightweight Directory Access Protocol (LDAP),轻型目录访问协议是一个访问在线目录服务的协议。下面的例子中简单介绍在java中队...
    99+
    2022-11-15
    JAVA LDAP
  • 通过python-ldap处理ldap服
        最近项目中加入LDAP认证方式,那么问题来了,在网站上创建用户的时候,要将用户同步到LDAP服务器上。看了一下python-ldap的文档,实现了对ldap服务器上的用户实现增删改查。 import ldap from rest...
    99+
    2023-01-31
    python ldap
  • node.js下LDAP查询实例分享
    目标: 从一个LDAP Server获取uid=kxh的用户数据 LDAP地址为:ldap://10.233.21.116:389 在工程根目录中,先npm一个LDAP的访问库ldpajs npm inst...
    99+
    2022-06-04
    实例 node js
  • mac安装python-ldap
    升级了mac操作系统,安装python的python-ldap,报错Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found#include <sasl.h>...
    99+
    2023-01-31
    mac python ldap
  • 使用 Python-LDAP 操作 LD
    转自:http://www.vpsee.com/ 周末看到那些排队血拼的人们,不用走进 shopping mall、不用看到那些五颜六色的打折和视觉冲击就能感受到 “节日要到了!”。一年又快结束了,这周完成备份、升级之类的收尾工作,接...
    99+
    2023-01-31
    操作 Python LDAP
  • Python使用LDAP做用户认证
    LDAP(Light Directory Access Portocol)是轻量目录访问协议,基于X.500标准,支持TCP/IP。 LDAP目录以树状的层次结构来存储数据。每个目录记录都有标识名(Distinguished Name,简...
    99+
    2023-01-30
    用户 Python LDAP
  • Python对接LDAP/AD的过程详解
    不同公司的 LDAP/AD 服务配置各不相同,很难封装一个通用的方法,所以我们在对接 LDAP/AD 的过程中,需要了解自己公司的 LDAP/AD 服务配置是怎么样的,才能写出正确的对接代码,因此下面...
    99+
    2023-09-13
    python 服务器 LDAP AD 认证
  • python实例
    Django使用mysql操作实战系列之七原创 2017年06月27日 16:46:04 标签:django /mysql 7211,创建项目test03创建项目test03。django-admin startproject test03...
    99+
    2023-01-31
    实例 python
  • 如何使用FreeRadius +LDAP实现验证功能
    这篇文章将为大家详细讲解有关如何使用FreeRadius +LDAP实现验证功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。------ LDAP 的部份 ---------  首先,當然是要...
    99+
    2023-06-03
  • CCF-CSP真题《202303-3 LDAP》思路+python,c++满分题解
    想查看其他题的真题及题解的同学可以前往查看:CCF-CSP真题附题解大全 试题编号:202303-3试题名称:LDAP时间限制:12.0s内存限制:1.0GB问题描述: 题目背景 西西艾弗岛运营公司是一家负责维护和运营岛上基础设施的...
    99+
    2023-09-01
    python c++ 开发语言
  • python小实例
    #!/usr/bin/pythonimport osimport rehosts = open('/home/haoren/serverlist.ini')for line in hosts:    if re.search('=',lin...
    99+
    2023-01-31
    实例 python
  • python web实例
    #引入包 import web #定义访问路径 urls = ( '/(.*)', 'hello' ) #定义app app = web.application(urls, globals()) ...
    99+
    2023-01-31
    实例 python web
  • python实例手册
    python实例手册更新下载地址:  http://url.cn/U7NUNf请使用 notepad++  设置 - 首选项 - 新建 - 选择utf8(无bom)格式。"alt+0"将函数折叠后方便查阅。...
    99+
    2023-01-31
    实例 手册 python
  • Python单例模式实例详解
    本文实例讲述了Python单例模式。分享给大家供大家参考,具体如下: 单例模式:保证一个类仅有一个实例,并提供一个访问他的全局访问点。 实现某个类只有一个实例的途径: 1,让一个全局变量使得一个对象被访问,...
    99+
    2022-06-04
    详解 实例 模式
  • python 编程实例 1
    #python 100 例 1.py#题目:有 1、2、3、4 个数字,能组成多少个互不相同且无重复数字的三位数?都是多 #少?a = {}c = 1for i in range(1,5):    for j in range(1,5): ...
    99+
    2023-01-31
    实例 python
  • Python numpy.trapz实例讲解
    `numpy.trapz()`函数是NumPy库中的一个函数,用于计算给定数据的定积分,即通过数值积分的方法来计算函数在给定区间上的...
    99+
    2023-10-12
    Python
  • python GUI实例学习
    在学习本篇之前,如果你对Python下进行GUI编程基础内容还有不明白,推荐一篇相关文章:简单介绍利用TK在Python下进行GUI编程的教程 写一个简单的界面很容易,即使是什么都不了解的情况下,这个文本转...
    99+
    2022-06-04
    实例 python GUI
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作