使用用户名作为变量的LDAP搜索 [英] LDAP search with username as variable

查看:194
本文介绍了使用用户名作为变量的LDAP搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python-LDAP模块并尝试对登录的用户进行查询.用户名将被传递到查询中.当我只输入用户名作为字符串时,我的结果就会正确显示出来.

I am using the Python-LDAP module and trying to make a query on the logged in user. The username will be passed into the query. When I simply type the username in as a string my results come out correctly.

但是如果我尝试传递(username)变量,它将返回 LDAPError - FILTER_ERROR: {'desc': u'Bad search filter'} 我尝试了多种不同的组合,但继续收到返回的相同错误.这里的任何见解都会很棒!

But if I try to pass the (username) variable it returns LDAPError - FILTER_ERROR: {'desc': u'Bad search filter'} I've tried a number of different combinations but continue to get the same error returned. Any insight here would be great!

针对最小,完整和可验证的示例进行了

Edited for Minimal, Complete, and Verifiable example:

import ldap

LDAP_SERVER = "ldap://myldapserver.domain.ad:389"
username = r"domain\serviceAccount"
password = "Password"

l = ldap.initialize(LDAP_SERVER)
def login(username, password):
    try:
        l.simple_bind_s(username, password)
        base = "OU=Users,OU=Group,DC=domain,DC=ad"

        criteria = "(&(objectClass=user)(sAMAccountName=anActualUsername))" #WORKS    
        criteria = '(&(objectClass=user)(sAMAccountName=%s))' % username #DOESNT WORK
        criteria = "(&(objectClass=user)" + "(sAMAccountName=" + username + "))" #DOESNT WORK

        attributes = ['displayName']
        result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)
        print result
    except ldap.INVALID_CREDENTIALS:
        return False
    return True

login(username,password)

推荐答案

我需要使用ldap.filter.filter_format进行正确的字符转义.

I needed to use ldap.filter.filter_format for proper character escaping.

import ldap.filter

criteria= ldap.filter.filter_format('(&(objectClass=user)(sAMAccountName=%s))', [username])

这篇关于使用用户名作为变量的LDAP搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆