How to retrieve all the attributes of LDAP database

2024/10/10 12:24:27

I am using ldap module of python to connect to ldap server. I am able to query the database but I dont know how to retrieve the fields present in the database, so that I can notify the user in advance to quering the database, telling him that the field he is trying to access is not in the database.

For example if the fields present are just

cn
memberOf

and if the user tries to query the database with filter

cn and memberOf and notcontained

I should be able to know that the notcontained attribute is not in the dabase schema.

How can I accomplish this.

Thanks.

Answer

You need to read the schema of your ldap server.

This code may work for you, as tempalte

#!/usr/bin/env python
#coding:utf-8
# Author:  peter --<[email protected]>
# Purpose: Tareas comunes a utilizar con respecto a schemas ldap
# Created: 01/05/12
import ldap
import ldap.schema########################################################################
class SchemasIPA(object):__ldaps = ldap.schema#----------------------------------------------------------------------def __init__(self, url):"""Constructor"""ldap._trace_level = 0ldap.set_option(ldap.OPT_DEBUG_LEVEL,0)subschemasubentry_dn, self.schema = ldap.schema.urlfetch(url,ldap._trace_level)self.oc_tree = self.schema.tree(ldap.schema.ObjectClass)        self.at_tree = self.schema.tree(ldap.schema.AttributeType)        def getobjectclasses(self):"""trae la listas de objectclasses de un servidor dado"""allobjc = {}for a in self.oc_tree.keys():objc = self.schema.get_obj(ldap.schema.ObjectClass, a)if objc != None:allobjc[objc.oid] = (objc.names, objc.must, objc.may, objc.sup, objc.obsolete)return allobjcdef getatributes(self):"""trae la lista de atributos de un servidor dado"""allatt= {}o = []for a in self.at_tree.keys():att = self.schema.get_obj(ldap.schema.AttributeType, a)if att != None:allatt[att.oid] = (att.names, att.syntax, att.syntax_len, att.desc, att.collective, att.equality, att.single_value)return allattdef getvalidoid(self, objects):"""retorno un valor oid libre valida para la creacion de esquemas y atributosel proceso valido es pedirle a la iana un oid valido, pero se tarda mas de un meslos oid a utilizar son valores predefinidos al momento de la instalacion del servidor ldap"""passif __name__ == '__main__':sch = SchemasIPA('ldap://localhost')#at = sch.getatributes()ob = sch.getobjectclasses()for a, b in ob.iteritems():print aprint b[0]

Then you can wrapper this class like this

#a file contained the above class
import schemasolschemas = schemas.SchemasIPA(url='ldap://192.168.1.81')#here are, some magic :)
pa = olschemas.schema.get_obj(olschemas._SchemasIPA__ldaps.ObjectClass, 'posixaccount')
pa.must #going to print all the attributes that can't be null's
pa.may #going to print all the attributes that are optional's
https://en.xdnf.cn/q/69891.html

Related Q&A

Why would this dataset implementation run out of memory?

I follow this instruction and write the following code to create a Dataset for images(COCO2014 training set)from pathlib import Path import tensorflow as tfdef image_dataset(filepath, image_size, batch…

Paramiko: Creating a PKey from a public key string

Im trying to use the SSH protocol at a low level (i.e. I dont want to start a shell or anything, I just want to pass data). Thus, I am using Paramikos Transport class directly.Ive got the server side d…

Appending to the end of a file in a concurrent environment

What steps need to be taken to ensure that "full" lines are always correctly appended to the end of a file if multiple of the following (example) program are running concurrently.#!/usr/bin/e…

Cython Pickling in Package not found as Error

Im having trouble pickling a Cython class, but only when its defined inside a package. This problem was noted previously online, but they didnt state how it was resolved. There are two components here:…

How can I process images faster with Python?

Id trying to write a script that will detect an RGB value on the screen then click the x,y values. I know how to perform the click but I need to process the image a lot faster than my code below curren…

KFolds Cross Validation vs train_test_split

I just built my first random forest classifier today and I am trying to improve its performance. I was reading about how cross-validation is important to avoid overfitting of data and hence obtain bett…

Using Keras, how can I input an X_train of images (more than a thousand images)?

My application is accident-avoidance car systems using Machine Learning (Convolutional Neural Networks). My images are 200x100 JPG images and the output is an array of 4 elements: the car would move le…

Fastest way to merge two deques

Exist a faster way to merge two deques than this?# a, b are two deques. The maximum length # of a is greater than the current length # of a plus the current length of bwhile len(b):a.append(b.poplef…

Python cannot find shared library in cron

My Python script runs well in the shell. However when I cron it (under my own account) it gives me the following error:/usr/local/bin/python: error while loading shared libraries: libpython2.7.so.1.0: …

Multiple async unit tests fail, but running them one by one will pass

I have two unit tests, if I run them one by one, they pass. If I run them at class level, one pass and the other one fails at response = await ac.post( with the error message: RuntimeError: Event loop…