Technical

Basic LDAP actions using Python

featured

If for some reason you want to perform basic actions on your LDAP server, be it for troubleshooting or integration with and app you’re writing, and you don’t really know what data to expect. Then I’ve got some code for you that you can execute quick and easy in a python shell.

First, let’s pick up the python ldap lib by running

pip install python-ldap

Then you can fire up a python shell and start fiddling.

########## initialize connection ###############################################

import ldap
con = ldap.initialize('ldap://127.0.0.1')

# At this point, we're connected as an anonymous user
# If we want to be associated to an account
# you can log by binding your account details to your connection

con.simple_bind_s("cn=admin,dc=example,dc=com", "my_password")

########## performing a simple ldap query ####################################

ldap_base = "dc=example,dc=com"
query = "(uid=maarten)"
result = con.search_s(ldap_base, ldap.SCOPE_SUBTREE, query)

########## adding (a user) ####################################################
# make sure all input strings are str and not unicode
# (it doesn't like unicode for some reason)
# each added attribute needs to be added as a list

dn = "uid=maarten,ou=people,dc=example,dc=com"
modlist = {
           "objectClass": ["inetOrgPerson", "posixAccount", "shadowAccount"],
           "uid": ["maarten"],
           "sn": ["De Paepe"],
           "givenName": ["Maarten"],
           "cn": ["Maarten De Paepe"],
           "displayName": ["Maarten De Paepe"],
           "uidNumber": ["5000"],
           "gidNumber": ["10000"],
           "loginShell": ["/bin/bash"],
           "homeDirectory": ["/home/maarten"]}
          }
# addModList transforms your dictionary into a list that is conform to ldap input.
result = con.add_s(dn, ldap.modlist.addModlist(modlist))

########## modifying (a user) ##########
# this works a bit strange.
# in a rel. database you just give the new value for the record you want to change
# here you need to give an old/new pair

dn = "uid=maarten,ou=people,dc=example,dc=com"
# you can expand this list with whatever amount of attributes you want to modify
old_value = {"loginShell": ["/bin/bash"]}
new_value = {"loginShell": ["/bin/zsh"]}

modlist = ldap.modlist.modifyModlist(old_value, new_value)
con.modify_s(dn, modlist)

########## modifying (the user's password) ##########
dn = "uid=maarten,ou=people,dc=example,dc=com"
con.passwd_s(dn, "my_old_password", "my_new_password")
# credit to Quanah Gibson-Mount for pointing out that this is the correct way to change a user's password

########## deleting (a user) #################################################
dn = "uid=maarten,ou=people,dc=example,cd=com"
con.delete_s(dn)