Python ldap.VERSION3 Examples
The following are 16
code examples of ldap.VERSION3().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ldap
, or try the search function
.
Example #1
Source File: ldapadmin.py From diting with GNU General Public License v2.0 | 6 votes |
def __ldap_getgid(self, cn="员工"): """ 查询 组cn对应的gid :param cn: 组cn :return: 对应cn的gidNumber """ obj = self.ldapconn obj.protocal_version = ldap.VERSION3 searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = None searchFilter = "cn=" + cn try: ldap_result_id = obj.search( base="%s" % self.base_dn, scope=searchScope, filterstr=searchFilter, attrlist=retrieveAttributes ) result_type, result_data = obj.result(ldap_result_id, 0) if result_type == ldap.RES_SEARCH_ENTRY: return result_data[0][1].get('gidNumber')[0] else: return None except ldap.LDAPError as e: logger.error('获取gid失败,原因为: %s' % str(e))
Example #2
Source File: ldapadmin.py From diting with GNU General Public License v2.0 | 6 votes |
def ldap_update_password(self, uid, new_password=None, old_password=None): """ 更新密码 :param uid: 用户uid,新password :return: True|None """ result = None try: obj = self.ldapconn obj.protocal_version = ldap.VERSION3 modifyDN = "uid=%s,%s" % (uid, BASE_DN) new_password_encrypt = pass_encrypt(new_password) #有old_password情况下 if old_password: obj.passwd_s(modifyDN, [str(old_password).encode('utf-8')], [new_password_encrypt.encode('utf-8')]) result = True else: obj.modify_s(modifyDN, [(ldap.MOD_REPLACE, 'userPassword', [new_password_encrypt.encode('utf-8')])]) result = True obj.unbind_s() except ldap.LDAPError as e: logger.error("%s 密码更新失败,原因为: %s" % (uid, str(e))) return False return result
Example #3
Source File: ldap.py From Adminset_Zabbix with Apache License 2.0 | 6 votes |
def ldap_search_dn(self,uid=None): obj = self.ldapconn obj.protocal_version = ldap.VERSION3 searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = None searchFilter = "cn=" + uid try: ldap_result_id = obj.search(self.base_dn, searchScope, searchFilter, retrieveAttributes) result_type, result_data = obj.result(ldap_result_id, 0) #返回数据格式 #('cn=django,ou=users,dc=gccmx,dc=cn', # { 'objectClass': ['inetOrgPerson', 'top'], # 'userPassword': ['{MD5}lueSGJZetyySpUndWjMBEg=='], # 'cn': ['django'], 'sn': ['django'] } ) # if result_type == ldap.RES_SEARCH_ENTRY: #dn = result[0][0] return result_data[0][0] else: return None except ldap.LDAPError, e: print e #查询用户记录,返回需要的信息
Example #4
Source File: ldap.py From Adminset_Zabbix with Apache License 2.0 | 6 votes |
def ldap_get_user(self,uid=None): obj = self.ldapconn obj.protocal_version = ldap.VERSION3 searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = None searchFilter = "cn=" + uid try: ldap_result_id = obj.search(self.base_dn, searchScope, searchFilter, retrieveAttributes) result_type, result_data = obj.result(ldap_result_id, 0) if result_type == ldap.RES_SEARCH_ENTRY: username = result_data[0][1]['cn'][0] email = result_data[0][1]['mail'][0] nick = result_data[0][1]['sn'][0] result = {'username':username,'email':email,'nick':nick} return result else: return None except ldap.LDAPError, e: print e #用户验证,根据传递来的用户名和密码,搜索LDAP,返回boolean值
Example #5
Source File: ldap.py From kqueen with MIT License | 6 votes |
def __init__(self, *args, **kwargs): """ Implementation of :func:`~kqueen.auth.base.__init__` """ super(LDAPAuth, self).__init__(*args, **kwargs) if not all(hasattr(self, attr) for attr in ['uri', 'admin_dn', '_password']): msg = 'Failed to configure LDAP, please provide valid LDAP credentials' logger.error(msg) raise ImproperlyConfigured(msg) # Define Kqueen rdn for all dc's d_names = ldap.dn.explode_dn(self.admin_dn) dc_list = [dc for dc in d_names if dc.startswith('dc=')] self.kqueen_dc = ','.join(dc_list) # Bind connection for Kqueen Read-only user if self._bind(self.admin_dn, self._password): self.connection = ldap.initialize(self.uri) self.connection.simple_bind_s(self.admin_dn, self._password) self.connection.protocol_version = ldap.VERSION3 else: msg = 'Failed to bind connection for Kqueen Read-only user' logger.error(msg) raise ImproperlyConfigured(msg)
Example #6
Source File: __init__.py From flask-simpleldap with MIT License | 6 votes |
def initialize(self): """Initialize a connection to the LDAP server. :return: LDAP connection object. """ try: conn = ldap.initialize('{0}://{1}:{2}'.format( current_app.config['LDAP_SCHEMA'], current_app.config['LDAP_HOST'], current_app.config['LDAP_PORT'])) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, current_app.config['LDAP_TIMEOUT']) conn = self._set_custom_options(conn) conn.protocol_version = ldap.VERSION3 if current_app.config['LDAP_USE_TLS']: conn.start_tls_s() return conn except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
Example #7
Source File: user_management.py From fame with GNU General Public License v3.0 | 5 votes |
def _ldap_get_con(): if not _check_ldap_settings_present(): return None con = ldap.initialize(fame_config.ldap_uri) con.protocol_version = ldap.VERSION3 con.set_option(ldap.OPT_REFERRALS, 0) return con
Example #8
Source File: config.py From ssh-ldap-pubkey with MIT License | 5 votes |
def __init__(self, path): """Initialize new LdapConfig with options parsed from config file on the ``path``. Arguments: path (Optional[path]): Path to the config file to read and parse. If not provided, then empty config is initialized. """ conf = parse_config_file(path) if path else {} if 'uri' in conf: self.uris = conf['uri'].split() else: host = conf.get('host', DEFAULT_HOST) port = conf.get('port', DEFAULT_PORT) self.uris = ["ldap://%s:%s" % (host, port)] self.base = conf.get('nss_base_passwd', '').split('?')[0] or conf.get('base', None) self.bind_dn = conf.get('binddn', None) self.bind_pass = conf.get('bindpw', None) self.bind_timeout = int(conf.get('bind_timelimit', DEFAULT_TIMEOUT)) self.cacert_dir = conf.get('tls_cacertdir', None) self.filter = conf.get('pam_filter', DEFAULT_FILTER) self.ldap_version = int(conf.get('ldap_version', ldap.VERSION3)) self.login_attr = conf.get('pam_login_attribute', DEFAULT_LOGIN_ATTR) self.pubkey_attr = conf.get('pubkey_attr', DEFAULT_PUBKEY_ATTR) self.pubkey_class = conf.get('pubkey_class', DEFAULT_PUBKEY_CLASS) self.referrals = parse_bool(conf.get('referrals', DEFAULT_REFERRALS)) self.sasl = conf.get('sasl', None) self.scope = parse_scope_opt(conf.get('scope', DEFAULT_SCOPE)) self.search_timeout = int(conf.get('timelimit', DEFAULT_TIMEOUT)) self.ssl = conf.get('ssl', None) self.tls_require_cert = parse_tls_reqcert_opt(conf.get('tls_reqcert'))
Example #9
Source File: ldap.py From zoe with Apache License 2.0 | 5 votes |
def __init__(self, conf, sasl): self.connection = ldap.initialize(conf.ldap_server_uri) self.base_dn = conf.ldap_base_dn self.sasl = sasl self.connection.protocol_version = ldap.VERSION3 if self.sasl: self.sasl_auth = ldap.sasl.sasl({}, 'GSSAPI')
Example #10
Source File: __init__.py From zentral with Apache License 2.0 | 5 votes |
def get_ldap_connection(host): conn = ldap.initialize("ldap://{}".format(host)) conn.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3) conn.start_tls_s() return conn
Example #11
Source File: user.py From PowerDNS-Admin with MIT License | 5 votes |
def ldap_init_conn(self): ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) conn = ldap.initialize(Setting().get('ldap_uri')) conn.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF) conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3) conn.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND) conn.set_option(ldap.OPT_X_TLS_DEMAND, True) conn.set_option(ldap.OPT_DEBUG_LEVEL, 255) conn.protocol_version = ldap.VERSION3 return conn
Example #12
Source File: login.py From loggrove with MIT License | 5 votes |
def ldap_auth_login(self): _ldap = self.application.settings.get('ldap') try: conn = ldap.initialize(_ldap.get('server_uri')) conn.protocal_version = ldap.VERSION3 conn.simple_bind_s(_ldap.get('bind_dn'), _ldap.get('bind_password')) except Exception as e: logging.error('Initialize Bind ldap failed: %s' % str(e)) response_data = dict(code=500, msg='Login failed') else: scope_subtree = ldap.SCOPE_SUBTREE filterstr = '(uid=%s)' % self.username result_id = conn.search(_ldap.get('base_dn'), scope_subtree, filterstr, None) result_type, result_data = conn.result(result_id, 0) if not result_data: response_data = dict(code=401, msg='Username or password incorrect') else: try: conn.simple_bind_s(result_data[0][0], self.password) except Exception as e: logging.error('Bind ldap user failed: %s' % str(e)) response_data = dict(code=401, msg='Username or password incorrect') else: self.ldap_user = result_data[0][1] user = self.base_user() # loggrove base user if not user: response_data = dict(code=500, msg='Login failed') elif user.get('status') != 1: response_data = dict(code=403, msg='User disabled') else: response_data = self.login(user) conn.unbind_s() return response_data
Example #13
Source File: ldapadmin.py From diting with GNU General Public License v2.0 | 5 votes |
def ldap_search_dn(self, value=None, value_type='uid'): """ # 根据表单提交的用户名,检索该用户的dn,一条dn就相当于数据库里的一条记录。 # 在ldap里类似cn=username,ou=users,dc=gccmx,dc=cn,验证用户密码,必须先检索出该DN :param value: 用户 uid或 组cn :param value_type: 用户 uid|cn :return: search result """ obj = self.ldapconn obj.protocal_version = ldap.VERSION3 searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = None if value_type == 'cn': searchFilter = "cn=" + value else: searchFilter = "uid=" + value try: ldap_result_id = obj.search( base=self.base_dn, scope=searchScope, filterstr=searchFilter, attrlist=retrieveAttributes ) result_type, result_data = obj.result(ldap_result_id, 0) if result_type == ldap.RES_SEARCH_ENTRY: return result_data else: return None except ldap.LDAPError as e: logger.error('ldap search %s 失败,原因为: %s' % (value, str(e)))
Example #14
Source File: ldapadmin.py From diting with GNU General Public License v2.0 | 5 votes |
def __get_max_uidNumber(self): """ 查询 当前最大的uid,这个是在添加用户时,用于自增uid :param: None :return: max uidNumber """ obj = self.ldapconn obj.protocal_version = ldap.VERSION3 searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = ['uidNumber'] searchFilter = "uid=*" try: ldap_result = obj.search( base="%s" % self.base_dn, scope=searchScope, filterstr=searchFilter, attrlist=retrieveAttributes ) print(ldap_result) result_set = [] while True: result_type, result_data = obj.result(ldap_result, 0) if not result_data: break else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(int(result_data[0][1].get('uidNumber')[0])) return max(result_set) + 1 except ldap.LDAPError as e: logger.error('获取最大uid失败,原因为: %s' % str(e))
Example #15
Source File: ldapadmin.py From diting with GNU General Public License v2.0 | 5 votes |
def ldap_add_user(self, cn, mail, username, password): """ 添加ldap用户 :param cn: 中文名, mail: 邮箱, username: 用户名, password: 密码 :return: True/None """ result = None try: obj = self.ldapconn obj.protocal_version = ldap.VERSION3 password_encrypt = pass_encrypt(password) addDN = "uid=%s,%s" % (username, BASE_DN) attrs = {} attrs['objectclass'] = ['inetOrgPerson'.encode('utf-8')] attrs['cn'] = [str(cn).encode('utf-8')] # attrs['homeDirectory'] = str('/home/%s' % username) # attrs['loginShell'] = '/bin/bash' attrs['mail'] = [str(mail).encode('utf-8')] attrs['sn'] = [str(username).encode('utf-8')] attrs['uid'] = [str(username).encode('utf-8')] attrs['userPassword'] = [str(password_encrypt).encode('utf-8')] # attrs['uidNumber'] = str(self.__get_max_uidNumber()) # attrs['gidNumber'] = self.__ldap_getgid(cn='员工') ldif = ldap.modlist.addModlist(attrs) obj.add_s(addDN, ldif) obj.unbind_s() result = True except ldap.LDAPError as e: logger.error("生成用户%s 失败,原因为: %s" % (username, str(e))) return result
Example #16
Source File: ldapadmin.py From diting with GNU General Public License v2.0 | 5 votes |
def ldap_delete(self, uid): try: obj = self.ldapconn obj.protocol_version = ldap.VERSION3 dn = "uid=%s,%s" % (uid, BASE_DN) obj.delete_s(dn) return True except ldap.LDAPError as e: logger.error("删除用户%s 失败,原因为: %s" % (uid, str(e))) return False