Normal command line LDAP tools such as ldapsearch, ldapadd, ldapmodify etc are handy when you are playing with standalone data. But if you want to do operations such as, taking user data from CSV in LDAP or get a neat formatted output for LDAP queries then python-ldap module is really what you need.
Here is how you install python-ldap module
pip3 install python-ldap
Collecting python-ldap
Downloading python-ldap-3.2.0.tar.gz (367 kB)
|████████████████████████████████| 367 kB 536 kB/s
Requirement already satisfied: pyasn1>=0.3.7 in /usr/local/lib/python3.7/site-packages (from python-ldap) (0.4.7)
Requirement already satisfied: pyasn1_modules>=0.1.5 in /usr/local/lib/python3.7/site-packages (from python-ldap) (0.2.8)
Installing collected packages: python-ldap
Running setup.py install for python-ldap ... done
Successfully installed python-ldap-3.2.0
Here is quick code to query LDAP server to fetch uid and mail of all uid objects in a given basedDN.
#!/usr/local/bin/python3
import ldap
try:
conn = ldap.initialize("ldap://xx.xx.xx.xx:389/")
conn.simple_bind_s("cn=myadmin","mypass")
except ldap.LDAPError as err:
print(err)
baseDN = "ou=myorg,dc=company,dc=in"
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = ["uid", "mail"]
searchFilter = "uid=*"
try:
ldap_result_id = conn.search(baseDN, searchScope, searchFilter, retrieveAttributes)
# if you want to colate all results in a single list use result_set
# result_set = []
while conn:
result_type, result_data = conn.result(ldap_result_id, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
dn = result_data[0][0]
data = result_data[0][1]
print(dn, data)
# result_set.append(result_data)
# print(result_set)
except ldap.LDAPError as err:
print(err)
# close connection
conn.unbind_s()
I will add more operations soon…..