Install Python-LDAP
sudo apt-get install python-ldap
OR
yum install python-ldap
Create
def ldap_add(firstname, lastname, username):
l = ldap.open(LDAP_HOST)
l.protocol_version = ldap.VERSION3
l.simple_bind(LDAP_BIND, LDAP_PASS)
cn = firstname + ' ' + lastname
addDN = "cn=%s,ou=People,dc=vpsee,dc=com" % cn
attrs = {}
attrs['objectclass'] = ['top','person','inetOrgPerson','posixAccount','vpseeAccount']
attrs['cn'] = cn
attrs['givenName'] = firstname
attrs['homeDirectory'] = '/home/people/%s' % username
attrs['loginShell'] = '/bin/bash'
attrs['sn'] = lastname
attrs['uid'] = username
attrs['uidNumber'] = ldap_newuid()
attrs['gidNumber'] = ldap_getgid()
attrs['active'] = 'TRUE'
ldif = modlist.addModlist(attrs)
l.add_s(addDN, ldif)
l.unbind_s()
Search & Read
Search or read a LDAP entry, for example - find CN though username:
def ldap_getcn(username):
try:
l = ldap.open(LDAP_HOST)
l.protocol_version = ldap.VERSION3
l.simple_bind(LDAP_BIND, LDAP_PASS)
searchScope = ldap.SCOPE_SUBTREE
searchFilter = "uid=*" + username + "*"
resultID = l.search(LDAP_BASE, searchScope, searchFilter, None)
result_set = []
while 1:
result_type, result_data = l.result(resultID, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
return result_set[0][0][1]['cn'][0]
except ldap.LDAPError, e:
print e
Update
Update an Entry in LDAP, for example - update user's state from active to false:
def ldap_deactive(username):
try:
l = ldap.open(LDAP_HOST)
l.protocol_version = ldap.VERSION3
l.simple_bind(LDAP_BIND, LDAP_PASS)
deactiveDN = ("cn=%s," + LDAP_BASE) % ldap_getcn(username)
old = {'active':'TRUE'}
new = {'active':'FALSE'}
ldif = modlist.modifyModlist(old, new)
l.modify_s(deactiveDN, ldif)
l.unbind_s()
except ldap.LDAPError, e:
print e
Delete
Delete an entry in LDAP.
def ldap_delete(username):
try:
l = ldap.open(LDAP_HOST)
l.protocol_version = ldap.VERSION3
l.simple_bind(LDAP_BIND, LDAP_PASS)
deleteDN = ("cn=%s," + LDAP_BASE) % ldap_getcn(username)
l.delete_s(deleteDN)
except ldap.LDAPError, e:
print e