我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用ldap.initialize()。
def _ldap_connection(self): """ Context manager for ldap connections """ if self.no_verify: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) ldap_cxn = ldap.initialize('{0}'.format(self.uri)) ldap_cxn.protocol_version = 3 ldap_cxn.set_option(ldap.OPT_REFERRALS, 0) if self.tls and not self.uri.startswith('ldaps'): ldap_cxn.start_tls_s() yield ldap_cxn
def get_custom_ldap_group_members(ldap_settings, group_name): logger = utils.get_logger() ldap_server = ldap_settings["server"] ldap_base = ldap_settings["base"] get_uid = lambda x: x[1]["uid"][0] members = [] try: conn = LDAP.initialize(ldap_server) g_ldap_filter = ldap_settings[group_name] logger.debug("Searching members for %s: %s" % (group_name, g_ldap_filter)) items = conn.search_s(ldap_base, LDAP.SCOPE_SUBTREE, attrlist=['uid'], filterstr=g_ldap_filter) members = map(get_uid, items) except Exception, e: logger.error("Error getting custom group %s from LDAP: %s" % (group_name, e)) return members
def get_ldap_group_members(ldap_settings, group_name): # base:dc=example,dc=com # filter:(&(objectClass=posixGroup)(cn={group_name})) logger = utils.get_logger() ldap_server = ldap_settings["server"] ldap_base = ldap_settings["groups_base"] ldap_filter = "(&%s(%s={group_name}))" % (ldap_settings["groups_filter"], ldap_settings["groups_id"]) get_uid = lambda x: x.split(",")[0].split("=")[1] try: ad_filter = ldap_filter.replace('{group_name}', group_name) conn = LDAP.initialize(ldap_server) logger.debug("Searching members for %s: %s - %s - %s" % (group_name, ldap_server, ldap_base, ad_filter)) res = conn.search_s(ldap_base, LDAP.SCOPE_SUBTREE, ad_filter) except Exception, e: logger.error("Error getting group from LDAP: %s" % e) return map(get_uid, res[0][1]['uniqueMember'])
def get_ldap_groups(ldap_settings): '''Returns the a list of found LDAP groups filtered with the groups list in the settings ''' # filter:(objectClass=posixGroup) # base:ou=Group,dc=example,dc=com logger = utils.get_logger() ldap_server = ldap_settings["server"] ldap_base = ldap_settings["groups_base"] ldap_filter = ldap_settings["groups_filter"] ldap_groups = ldap_settings["groups"] get_uid = lambda x: x[1]["cn"][0] try: conn = LDAP.initialize(ldap_server) logger.debug("Searching groups: %s - %s - %s" % (ldap_server, ldap_base, ldap_filter)) res = conn.search_s(ldap_base, LDAP.SCOPE_SUBTREE, ldap_filter) return filter((lambda x: x in ldap_groups), map(get_uid, res)) except Exception, e: logger.error("Error getting groups from LDAP: %s" % e)
def authentication_ldap(self,username,password,returnObject=True): cfg=r.table('config').get(1).run(db.conn)['auth'] try: conn = ldap.initialize(cfg['ldap']['ldap_server']) id_conn = conn.search(cfg['ldap']['bind_dn'],ldap.SCOPE_SUBTREE,"uid=%s" % username) tmp,info=conn.result(id_conn, 0) user_dn=info[0][0] if conn.simple_bind_s(who=user_dn,cred=password): ''' config/ldapauth.py has the function you can change to adapt to your ldap ''' au=myLdapAuth() newUser=au.newUser(username,info[0]) return User(newUser) if returnObject else newUser else: return False except Exception as e: log.error("LDAP ERROR:",e) return False
def ldapAuthenticate(username, password): if settings.AUTH_LDAP_SERVER_URI is None: return False if settings.AUTH_LDAP_USER_DN_TEMPLATE is None: return False try: connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) connection.protocol_version = ldap.VERSION3 user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username} connection.simple_bind_s(user_dn, password) return True except ldap.INVALID_CREDENTIALS: return False except ldap.SERVER_DOWN: return False
def ldapAuthenticate(username, password): if settings.AUTH_LDAP_SERVER_URI is None: return False if settings.AUTH_LDAP_USER_DN_TEMPLATE is None: return False try: connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) connection.protocol_version = ldap.VERSION3 user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username} connection.simple_bind_s(user_dn, password) return True except ldap.INVALID_CREDENTIALS: return False except ldap.SERVER_DOWN: # TODO: Return error instead of none return False
def updateuser(self, uid, modattrs): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "uid=%s,%s" % (uid, self.config["memberdn"]) ldap_filter = "uid="+uid result_id = l.search(self.config["memberdn"], ldap.SCOPE_SUBTREE, ldap_filter, None) if result_id: type, data = l.result(result_id, 0) if data: dn, attrs = data[0] oldattrs = attrs newattrs = attrs.copy() newattrs.update(modattrs) # now change it newattrs.update(oldattrs) ldif = modlist.modifyModlist(oldattrs, newattrs) print ldif l.modify_s(dn, ldif) l.unbind_s() return True else: return False
def check_credentials(self, username, password): try: ldap_client = ldap.initialize(self.config["server"]) ldap_client.set_option(ldap.OPT_REFERRALS,0) ldap_client.simple_bind_s("uid=%s,%s" % (username, self.config["memberdn"]), password) except ldap.INVALID_DN_SYNTAX: ldap_client.unbind() return False except ldap.INVALID_CREDENTIALS: ldap_client.unbind() return False except ldap.UNWILLING_TO_PERFORM: ldap_client.unbind() return False except ldap.SERVER_DOWN: ldap_client.unbind() raise ServerDownException() return False ldap_client.unbind() return True
def initialize(uri,trace_level=0,trace_file=sys.stdout,trace_stack_limit=None, bytes_mode=None): """ Return LDAPObject instance by opening LDAP connection to LDAP host specified by LDAP URL Parameters: uri LDAP URL containing at least connection scheme and hostport, e.g. ldap://localhost:389 trace_level If non-zero a trace output of LDAP calls is generated. trace_file File object where to write the trace output to. Default is to use stdout. bytes_mode Whether to enable "bytes_mode" for backwards compatibility under Py2. """ return LDAPObject(uri,trace_level,trace_file,trace_stack_limit,bytes_mode)
def open(host,port=389,trace_level=0,trace_file=sys.stdout,trace_stack_limit=None,bytes_mode=None): """ Return LDAPObject instance by opening LDAP connection to specified LDAP host Parameters: host LDAP host and port, e.g. localhost port integer specifying the port number to use, e.g. 389 trace_level If non-zero a trace output of LDAP calls is generated. trace_file File object where to write the trace output to. Default is to use stdout. bytes_mode Whether to enable "bytes_mode" for backwards compatibility under Py2. """ import warnings warnings.warn('ldap.open() is deprecated! Use ldap.initialize() instead.', DeprecationWarning,2) return initialize('ldap://%s:%d' % (host,port),trace_level,trace_file,trace_stack_limit,bytes_mode)
def create_user_in_ldap(username, password, uidnumber): # Open a connection l = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) # Bind/authenticate with a user with apropriate rights to add objects l.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) # The dn of our new entry/object dn="cn="+ username +",dc=ldap,dc=portal,dc=com" #dn="cn=python_test,ou=People,dc=coegss,dc=hlrs,dc=de" ctx = sha.new(password) hash = "{SHA}" + b64encode(ctx.digest()) # A dict to help build the "body" of the object attrs = {} attrs['uid'] = [str(username)] attrs['uidNumber'] = [str(uidnumber+500)] attrs['gidNumber'] = ['100'] attrs['objectclass'] = ['inetOrgPerson','organizationalPerson','person','posixAccount','top'] attrs['cn'] = str(username) attrs['sn'] = str(username) attrs['userPassword'] = hash #attrs['description'] = 'test_python_user' attrs['homeDirectory'] = '/home/users/' + str(username) # Convert our dict to nice syntax for the add-function using modlist-module ldif = modlist.addModlist(attrs) # Do the actual synchronous add-operation to the ldapserver l.add_s(dn,ldif) # Disconnect and free resources when done l.unbind_s()
def ldap_initialize(module, server): ldapmodule_trace_level = 1 ldapmodule_trace_file = sys.stderr ldap._trace_level = ldapmodule_trace_level try: conn = ldap.initialize( server, trace_level=ldapmodule_trace_level, trace_file=ldapmodule_trace_file ) except ldap.LDAPError as e: fail_msg = "LDAP Error initializing: {}".format(ldap_errors(e)) module.fail_json(msg=fail_msg) return conn
def getDefaultNamingContext(self): try: newCon = ldap.initialize('ldap://{}'.format(self.dc_ip)) newCon.simple_bind_s('','') res = newCon.search_s("", ldap.SCOPE_BASE, '(objectClass=*)') rootDSE = res[0][1] except ldap.LDAPError, e: print "[!] Error retrieving the root DSE" print "[!] {}".format(e) sys.exit(1) if not rootDSE.has_key('defaultNamingContext'): print "[!] No defaultNamingContext found!" sys.exit(1) defaultNamingContext = rootDSE['defaultNamingContext'][0] self.domainBase = defaultNamingContext newCon.unbind() return defaultNamingContext
def _connect_to_ldap(self): ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) connection = ldap.initialize(self.server_uri) if self.start_tls: try: connection.start_tls_s() except ldap.LDAPError: e = get_exception() self.module.fail_json(msg="Cannot start TLS.", details=str(e)) try: if self.bind_dn is not None: connection.simple_bind_s(self.bind_dn, self.bind_pw) else: connection.sasl_interactive_bind_s('', ldap.sasl.external()) except ldap.LDAPError: e = get_exception() self.module.fail_json( msg="Cannot bind to the server.", details=str(e)) return connection
def connect(**kw): # Sources order, see ldap.conf(3) # variable $LDAPNOINIT, and if that is not set: # system file /etc/ldap/ldap.conf, # user files $HOME/ldaprc, $HOME/.ldaprc, ./ldaprc, # system file $LDAPCONF, # user files $HOME/$LDAPRC, $HOME/.$LDAPRC, ./$LDAPRC, # user files <ldap2pg.yml>... # variables $LDAP<uppercase option name>. # # Extra variable LDAPPASSWORD is supported. options = gather_options(**kw) logger.debug("Connecting to LDAP server %s.", options['URI']) l = ldap.initialize(options['URI']) if PY2: # pragma: nocover_py3 l = UnicodeModeLDAPObject(l) l = LDAPLogger(l) if options.get('USER'): logger.debug("Trying SASL DIGEST-MD5 auth.") auth = sasl.sasl({ sasl.CB_AUTHNAME: options['USER'], sasl.CB_PASS: options['PASSWORD'], }, 'DIGEST-MD5') l.sasl_interactive_bind_s("", auth) else: logger.debug("Trying simple bind.") l.simple_bind_s(options['BINDDN'], options['PASSWORD']) return l
def __ldap_bind(self): if not self.__ldap_conn: l = ldap.initialize(self.ldapserver) if self.ldaptls: l.start_tls_s() l.simple_bind_s(self.ldapbinddn, self.ldappasswd) self.__ldap_conn = l return self.__ldap_conn
def __init__(self, uri, cn, dc, secret): self.conn = None self.uri = uri self.dc = dc self.secret = secret try: self.conn = ldap.initialize(self.uri) self.conn.protocol_version = ldap.VERSION3 self.conn.simple_bind_s(cn+","+self.dc,self.secret) print("Connection established.") except ldap.INVALID_CREDENTIALS: print("Your username or password is incorrect.") sys.exit() except ldap.LDAPError as e: if type(e.message) == dict and e.message.has_key('desc'): print(e.message['desc']) else: print(e) sys.exit()
def login(username, password): from tuckshop.core.config import Config from tuckshop.app.models import User if 'TUCKSHOP_DEVEL' in environ and environ['TUCKSHOP_DEVEL']: # If tuckshop in development mode, match all passwords # again 'password' if password != 'password': return False else: # Otherwise authenticate against LDAP server ldap_obj = ldap.initialize('ldap://%s:389' % Config.LDAP_SERVER()) dn = 'uid=%s,%s' % (username, Config.LDAP_USER_BASE()) try: # Attempt to bind to LDAP ldap_obj.simple_bind_s(dn, password) except: # If the connection throws an exception, return False return False # Create user object for currently logged in user user_object = User.objects.filter(uid=username) # If a user object does not exist, create a new one if (not len(user_object)): user_object = User(uid=username) user_object.save() else: user_object = user_object[0] # Determine if the user account is a shared account. # If it is, do not allow the user to login if user_object.shared: return False # Return user object return user_object
def __init__( self,uri, trace_level=0,trace_file=None,trace_stack_limit=5 ): self._trace_level = trace_level self._trace_file = trace_file or sys.stdout self._trace_stack_limit = trace_stack_limit self._uri = uri self._ldap_object_lock = self._ldap_lock() self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri) self.timeout = -1 self.protocol_version = ldap.VERSION3
def reconnect(self,uri): # Drop and clean up old connection completely # Reconnect reconnect_counter = self._retry_max while reconnect_counter: if __debug__ and self._trace_level>=1: self._trace_file.write('*** Try %d. reconnect to %s...\n' % ( self._retry_max-reconnect_counter+1,uri )) try: # Do the connect self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri) self._restore_options() # StartTLS extended operation in case this was called before if self._start_tls: self.start_tls_s() # Repeat last simple or SASL bind self._apply_last_bind() except ldap.SERVER_DOWN,e: SimpleLDAPObject.unbind_s(self) del self._l if __debug__ and self._trace_level>=1: self._trace_file.write('*** %d. reconnect to %s failed\n' % ( self._retry_max-reconnect_counter+1,uri )) reconnect_counter = reconnect_counter-1 if not reconnect_counter: raise if __debug__ and self._trace_level>=1: self._trace_file.write('=> delay %s...\n' % (self._retry_delay)) time.sleep(self._retry_delay) else: if __debug__ and self._trace_level>=1: self._trace_file.write('*** %d. reconnect to %s successful, last operation will be repeated\n' % ( self._retry_max-reconnect_counter+1,uri )) self._reconnects_done = self._reconnects_done + 1L break
def adduser(self, attrs): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "uid=%s,%s" % (attrs["uid"], self.config["memberdn"]) attrs["objectClass"] = ['top', 'account', 'simpleSecurityObject', 'xxPilot'] attrs["userPassword"] = self.makeSecret(attrs["userPassword"]) ldif = modlist.addModlist(attrs) l.add_s(dn, ldif) l.unbind_s()
def addgroup(self, attrs): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "cn=%s,%s" % (attrs["cn"], self.config["groupdn"]) attrs["objectClass"] = ["groupofnames"] ldif = modlist.addModlist(attrs) print dn, ldif l.add_s(dn, ldif) l.unbind_s()
def deletegroup(self, group): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "cn=%s,%s" % (str(group), self.config["groupdn"]) l.delete_s(dn) l.unbind_s() return True
def modts3id(self, uid, change, ts3id): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "uid=%s,%s" % (uid, self.config["memberdn"]) l.modify_s(dn, [(change, 'ts3uid', ts3id)]) l.unbind_s() return True
def modattr(self, uid, change, attr, value): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "uid=%s,%s" % (uid, self.config["memberdn"]) l.modify_s(dn, [(change, str(attr), str(value))]) l.unbind_s() return True
def deleteuser(self, uid): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "uid=%s,%s" % (uid, self.config["memberdn"]) l.delete_s(dn) l.unbind_s() return True
def modgroup(self, uid, change, group): l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) dn = "uid=%s,%s" % (uid, self.config["memberdn"]) l.modify_s(dn, [(change, 'authGroup', group)]) l.unbind_s() return True
def getuser(self, id): if not isinstance(id, basestring): id = id[0] l = ldap.initialize(self.config["server"]) l.simple_bind(self.config["admin"], self.config["password"]) ldap_filter = "uid="+id result_id = l.search(self.config["memberdn"], ldap.SCOPE_SUBTREE, ldap_filter, None) if result_id: type, data = l.result(result_id, 0) if data: dn, attrs = data[0] l.unbind_s() return self.User(attrs, self.authconfig["auth"]["domain"]) l.unbind_s() return None
def ldap_connect(self,ip,username,password,port): creak=0 try: ldappath='ldap://'+ip+':'+port+'/' l = ldap.initialize(ldappath) re=l.simple_bind(username,password) if re==1: creak=1 except Exception,e: if e[0]['desc']=="Can't contact LDAP server": creak=2 pass return creak
def initiate_ldap(): """ contact the LDAP server to return a LDAP object """ ldap_schemes = ['ldap://', 'ldaps://'] ldap.set_option(ldap.OPT_DEBUG_LEVEL, 0) ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, config.get('ldap', 'cacertdir')) ldap.set_option(ldap.OPT_X_TLS_CERTFILE, config.get('ldap', 'certfile')) ldap.set_option(ldap.OPT_X_TLS_KEYFILE, config.get('ldap', 'keyfile')) ldap.set_option(ldap.OPT_X_TLS_DEMAND, True) ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND) # TRY, NEVER, DEMAND ldap.set_option(ldap.OPT_X_TLS_NEWCTX, 0) for scheme in ldap_schemes: ldap_url = scheme + server_url ldap_obj = ldap.initialize(ldap_url) try: ldap_obj.start_tls_s() except ldap.OPERATIONS_ERROR as e: e_msg = e[0]['info'] if e_msg == 'TLS already started': pass else: raise except ldap.SERVER_DOWN: if scheme is not ldap_schemes[-1]: continue else: raise if login_dn != 'DEFAULT': # Use anonymous bind if login_dn is set as DEFAULT ldap_obj.bind(login_dn, password, ldap.AUTH_SIMPLE) else: try: ldap_obj.whoami_s() except ldap.UNWILLING_TO_PERFORM: print 'Anonymous binding is disabled by server' raise SystemExit return ldap_obj break
def __init__( self,uri, trace_level=0,trace_file=None,trace_stack_limit=5,bytes_mode=None ): self._trace_level = trace_level self._trace_file = trace_file or sys.stdout self._trace_stack_limit = trace_stack_limit self._uri = uri self._ldap_object_lock = self._ldap_lock('opcall') self._l = ldap.functions._ldap_function_call(ldap._ldap_module_lock,_ldap.initialize,uri) self.timeout = -1 self.protocol_version = ldap.VERSION3 # Bytes mode # ---------- # By default, raise a TypeError when receiving invalid args self.bytes_mode_hardfail = True if bytes_mode is None and PY2: warnings.warn( "Under Python 2, python-ldap uses bytes by default. " "This will be removed in Python 3 (no bytes for DN/RDN/field names). " "Please call initialize(..., bytes_mode=False) explicitly.", BytesWarning, stacklevel=2, ) bytes_mode = True # Disable hard failure when running in backwards compatibility mode. self.bytes_mode_hardfail = False elif bytes_mode and not PY2: raise ValueError("bytes_mode is *not* supported under Python 3.") # On by default on Py2, off on Py3. self.bytes_mode = bytes_mode
def whoami_s(self,*args,**kwargs): return self._apply_method_s(SimpleLDAPObject.whoami_s,*args,**kwargs) # The class called LDAPObject will be used as default for # ldap.open() and ldap.initialize()
def ldap_auth(self, username, password): ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path) connection = ldap.initialize(self.ldap_url) connection.set_option(ldap.OPT_REFERRALS, 0) try: if password: connection.simple_bind_s(username + self.user_suffix, password) else: return False except ldap.INVALID_CREDENTIALS: return False except ldap.SERVER_DOWN: return None return True
def ldap_connection(username, password): conn = ldap.initialize(settings.LDAP_PROVIDER_URL) try: conn.simple_bind_s('uid={0},{1}'.format(username, settings.LDAP_BASE_DC), password) return 1 except: return 0
def __init__(self, backend, mode=PLAIN, cert=None, key=None, cacertdir='/etc/ssl/certs', ): self.backend = backend self._server = None self._schema = {} self._cert = cert self._key = key logger.debug("LDAP _session created, id: {}".format(id(self))) # Switch to LDAPS mode if ldaps is backend start with 'ldaps' if 'ldaps' == backend[:5].lower(): mode = self.LDAPS # Set CACERTDIR and REQUIRED_CERT to TLS_DEMAND (validation required) if needed if mode in (self.STARTTLS, self.LDAPS) and cacertdir is not None: ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, cacertdir) ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND) if cacertdir is None: warnings.warn("You are in INSECURE mode", ImportWarning, stacklevel=2) ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) # Set client certificate if both cert and key are provided if cert is not None and key is not None: if not os.path.isfile(cert): raise LDAPSessionException("Certificate file {} does not exist".format(cert)) if not os.path.isfile(key): raise LDAPSessionException("Certificate key file {} does not exist".format(cert)) ldap.set_option(ldap.OPT_X_TLS_CERTFILE, cert) ldap.set_option(ldap.OPT_X_TLS_KEYFILE, key) self._server = ldap.initialize(self.backend, bytes_mode=False) # Proceed STARTTLS if mode == self.STARTTLS: self._server.start_tls_s()
def __init__(self, uri, base, filter_pattern, scope=SCOPE_SUBTREE, tls=False, user="", passwd="", attr=None, attrsonly=False): UserInfo.__init__(self) self.ldapuri = uri self.base = base self.filter_pattern = filter_pattern self.scope = scope self.tls = tls self.attr = attr self.attrsonly = attrsonly self.ld = ldap.initialize(uri) self.ld.protocol_version = ldap.VERSION3 self.ld.simple_bind_s(user, passwd)
def __init__(self, srv, ldapsrv, return_to, dn_pattern, mako_template, template_lookup): """ :param srv: The server instance :param ldapsrv: Which LDAP server to us :param return_to: Where to send the user after authentication :return: """ UsernamePasswordMako.__init__(self, srv, mako_template, template_lookup, None, return_to) self.ldap = ldap.initialize(ldapsrv) self.ldap.protocol_version = 3 self.ldap.set_option(ldap.OPT_REFERRALS, 0) self.dn_pattern = dn_pattern
def initialize_connection(): connection = ldap.initialize(config.LDAP_SERVER_URI) connection.protocol_version = ldap.VERSION3 for key, value in config.LDAP_GLOBAL_OPTIONS.items(): connection.set_option(key, value) if config.LDAP_START_TLS: connection.start_tls_s() yield connection connection.unbind_s()
def __init__(self, username, password): ldap_host = "192.168.78.8" ldap_port = "389" ldaps_port = "636" ldap_enable_ldaps = False self.ldap_base_dn = "DC=example,DC=com,DC=cn" # example.com.cn self.ldap_user = username self.ldap_password = password if ldap_enable_ldaps is True: self.uri = "ldaps://" + ldap_host + ":" + ldaps_port else: self.uri = "ldap://" + ldap_host + ":" + ldap_port self.is_active = False self.user_data = None self.conn = ldap.initialize(self.uri) try: self.conn.set_option(ldap.OPT_REFERRALS, 0) # this option is required in Windows Server 2012 self.conn.simple_bind_s(who=self.ldap_user, cred=self.ldap_password) except ldap.INVALID_CREDENTIALS: raise Exception("Invalid credentials") except ldap.SERVER_DOWN: raise Exception("Can't contact LDAP server") self.is_active = True self.user_data = self.conn.search_s(self.ldap_base_dn, ldap.SCOPE_SUBTREE, 'userPrincipalName=' + self.ldap_user) # self.user_data = self.conn.search_s(self.ldap_base_dn, ldap.SCOPE_SUBTREE) self.conn.unbind()
def __init__(self): if not ldap: raise ImportError(_('ldap not installed')) self.lobj = ldap.initialize(CONF.ldap_dns_url) self.lobj.simple_bind_s(CONF.ldap_dns_user, CONF.ldap_dns_password)
def initializeConnection(self): if not self.dc_ip: self.dc_ip = self.getDC_IP(self.domain) con = ldap.initialize('ldap://{}'.format(self.dc_ip)) con.set_option(ldap.OPT_REFERRALS, 0) return con
def connect(self, uri=rbconfig.LDAP_URI, dn=rbconfig.LDAP_ROOT_DN, password=None, dcu_uri=rbconfig.LDAP_DCU_URI, dcu_dn=rbconfig.LDAP_DCU_RBDN, dcu_pw=None): """Connect to databases. Custom URI, DN and password may be given for RedBrick LDAP. Password if not given will be read from shared secret file set in rbconfig. Custom URI may be given for DCU LDAP. """ if not password: try: pw_file = open(rbconfig.LDAP_ROOTPW_FILE, 'r') password = pw_file.readline().rstrip() except IOError: raise RBFatalError("Unable to open LDAP root password file") pw_file.close() if not dcu_pw: try: pw_file = open(rbconfig.LDAP_DCU_RBPW, 'r') dcu_pw = pw_file.readline().rstrip() except IOError: raise RBFatalError("Unable to open DCU AD root password file") pw_file.close() # Default protocol seems to be 2, set to 3. ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3) # Connect to RedBrick LDAP. self.ldap = ldap.initialize(uri) self.ldap.simple_bind_s(dn, password) # Connect to DCU LDAP (anonymous bind). self.ldap_dcu = ldap.initialize(dcu_uri) # self.ldap_dcu.simple_bind_s('', '') self.ldap_dcu.simple_bind_s(dcu_dn, dcu_pw)