LDAP/AD是两种应用最广泛的认证服务器,AD是微软基于LDAP开发而成的,应用于Windows平台,而LDAP主要应用于Linux平台(LDAP用在Windows平台比较少)。既然AD是基于LDAP的扩展,则LDAP大部分协议,AD均可原生支持,这位我们操作和管理AD认证服务器提供了大大的便利。
在软件开发过程中,很多公司都采用AD/LDAP用于自己的用户认证体系,本文重点研究通过Python语言提供的Python-Ldap框架,来操作和管理AD/LDAP中的用户,组织结构等,希望对大家有所帮助。
基本概念:
o– organization(组织-公司)
ou – organization unit(组织单元/部门)
c - countryName(国家)
dc - domainComponent(域名组件)
sn – suer name(真实名称)
cn - common name(常用名称)
dn - distinguished name(唯一标识)
AD和LDAP中的字段及含义:
用户表字段对应关系:
字段描述 表示值
唯一标识 dn
用户名 userPrincipalName(AD)/cn(LDAP)
密码 userPassword
真实姓名 displayName
工作地点 physicalDeliveryOfficeName
职务 title
邮箱 mail
个人电话 telephoneNumber
公司电话 homePhone
组织结构表对应关系:
字段描述 表示值
唯一标识 dn
组织名称 ou
组织描述 description
在AD中创建用户
import ldap
def create_ad_user(username, unicode_password, org_dn):
l = ldap.initialize('ldap://172.16.1.163:636') #use secure port default:636
l.protocol_version = 3
l.set_option(ldap.OPT_REFERRALS, 0)
l.simple_bind_s('Administrator', 'P@ssword')
user = {}
user['objectclass'] = ['top', 'person', 'organizationalPerson', 'user']
user_dn = 'cn=%s,%s' % (username,org_dn)
user['userPrincipalName'] = '%s@%s' % (username, domain)
user['userAccountControl'] = '66048' # active user account
user['unicodePwd'] = unicode_password
ldif = modlist.addModlist(user)
ret, _ = l.add_s(user_dn, ldif)
print ret
在LDAP中创建用户
import ldap
def create_ldap_user(username, password, org_dn):
l = ldap.initialize('ldap://172.16.1.163:389')
l.protocol_version = 3
l.set_option(ldap.OPT_REFERRALS, 0)
l.simple_bind_s('Administrator', 'P@ssword')
user = {}
user['objectclass'] = ['top', 'person', 'inetOr