def __init__(self): """Bind to LDAP directory, return an ldap object.""" self.config = config.setup() self.log = logger.setup(__name__) self.search_scope = ldap.SCOPE_SUBTREE #(2) self.server = self.config.get('LDAP', 'server') self.port = self.config.get('LDAP', 'port', '389') self.bind_dn = self.config.get('LDAP', 'binddn') self.start_tls = self.config.get('LDAP', 'start_tls', False) self.bind_password = self.config.get('LDAP', 'bindpw') try: self.LDAP = ldap.initialize('ldap://%s:%s' % (self.server, self.port)) self.LDAP.protocol_version = 3 #ldap.VERSION3 if self.start_tls: self.LDAP.start_tls_s() self.LDAP.simple_bind_s(self.bind_dn, self.bind_password) self.log.debug('Bound to LDAP server %s:%s as %s' % (self.server, self.port, self.bind_dn)) except ldap.LDAPError: trace = traceback.format_exc() msg = 'Failed to bind to LDAP server %s:%s as %s' % \ (self.server,self.port, self.bind_dn) raise error.SpokeLDAPError(msg, trace) except Exception: trace = traceback.format_exc() msg = 'Unknown error' raise error.SpokeError(msg, trace)
def _create_object(self, dn, dn_info): """Create a new LDAP object (e.g. a dn or attribute).""" # Allowed LDAP operations operation = {'add':self.LDAP.add_s, 'mod':self.LDAP.modify_s} try: int(dn_info[0][0]) #attribute mod opertations begin with an integer. type = 'mod' attrlist = [] # Collect a list of attributes to return for item in dn_info: attrlist.append(item[1]) except: type = 'add' #if it's not a modification, it's an add operation. attrlist = None try: operation[type](dn, dn_info) except ldap.ALREADY_EXISTS: msg = 'Entry %s already exists.' % dn raise error.AlreadyExists(msg) except ldap.TYPE_OR_VALUE_EXISTS: msg = 'Attempt to add attribute to %s which already exists.' % dn raise error.AlreadyExists(msg) except ldap.CONSTRAINT_VIOLATION: msg = 'Attribute already exists and does not support multiples' raise error.AlreadyExists(msg) except ldap.NO_SUCH_OBJECT: msg = "Part of %s missing, can't create." % dn raise error.NotFound(msg) except ldap.LDAPError, e: trace = traceback.format_exc() raise error.SpokeLDAPError(e, trace)
# core modules import traceback # own modules import spoke.lib.error as error import spoke.lib.config as config import spoke.lib.logger as logger import spoke.lib.common as common # 3rd party modules try: import ldap import ldap.modlist except: msg = 'Failed to import ldap' raise error.SpokeLDAPError(msg) hLDAP = None def setup(): """Instantiate (once only) and return LDAP connection object""" global hLDAP if hLDAP is not None: pass else: hLDAP = SpokeLDAPConn() return hLDAP class SpokeLDAPConn: """Extend ldap class with convenience methods."""