Home > Software engineering >  Issue Querying LDAP from Unix Bash using Python
Issue Querying LDAP from Unix Bash using Python

Time:04-08

I am reading a csv file containing list of employees(GRCLOGIN.csv) and retrieving employee ID to Query LDAP to retrieve their related data and save it to a text file(LDAP_USERS.txt)

from sys import exit
import subprocess, sys
import csv

with open('GRCLOGIN.csv', 'r') as file:
    reader = csv.reader(file, quoting=csv.QUOTE_NONE, skipinitialspace=True)
    reader = csv.reader(file)
    output = open('LDAP_USERS.txt', 'a')
    next(reader)
    for row in reader:
       val=row[0]
       

This is where I am getting issue, my objective is only to retrieve employee's firstName and Email, not all details/columns, but when I include firstname and email in the query below , empty text file is generated, but if I remove firstname and email then text file is generated with all employees details correctly but I don't want all details.

I feel issue is where $1 is not correctly being set to str(val) which is employee ID

subprocess.Popen(["./ldapsearch -B -1 -T -h localhost -p 1389 -D 'cn=directory manager' -j ../../bin/passwordfile.txt -b '(GRCLoginID=$1)' firstName email" str(val)], stdout=output, stderr=output, shell=True)

exit()

CodePudding user response:

In a linux shell try ./ldapsearch --help, it would very usefull, besides that, if you want to only get certain attributes, you must put the attributes in the end of the command, and to only get one user, either you search with fixed search base, if you know where the user is in the ldap, otherwise you can search it by applying a filter on user id so:

["./ldapsearch -B -1 -T -h localhost -p 1389 -D 'cn=directory manager' -j ../../bin/passwordfile.txt -b 'GRCLoginID=$1,ou=users,cn=root,cn=com' firstName email", val]

["./ldapsearch -B -1 -T -h localhost -p 1389 -D 'cn=directory manager' -j ../../bin/passwordfile.txt -b 'cn=com' firstName email -f (&(GRCLoginID=$1))", val]

Both options are valid

CodePudding user response:

I would use the python ldap module for this. You will receive the results within python immediately without the CSV in between.

import ldap

ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
ldapurl = "ldap://server:port"
conn = ldap.initialize(ldapurl)
# connect to the server
conn.simple_bind_s(username, password)
# return these attributes
returntome = ('firstName', 'email')
# Use this search filter
ldapfilter = 'GRCLoginID=' val
# Start searching
results = conn.search_s( 'cn=com', ldap.SCOPE_SUBTREE, ldapfilter, returntome )

Now the results variable contains a list of LDAP objects that you can iterate over in Python. See the documentation at https://www.python-ldap.org/en/python-ldap-3.4.0/reference/ldap.html#ldap.LDAPObject.search

  • Related