본문 바로가기

Python/LDAP

python-ldap

LDAP 접속 인증

import ldap 
ld = ldap.initialize('ldap://ldapaddress:port') 
ld.set_option(ldap.OPT_REFERRALS, 0) 
ld.simple_bind_s('계정명속성이름=Accountname','password') 

값비교

# 기본적인 비교
ld.compare_s('uid=UserID,ou=user,dc=example,dc=com', '비교할속성이름', '기대값')
#  1 = same, 0 = not same
 
ld.compare_s('uid=UserID,ou=user,dc=example,dc=com', '비밀번호속성이름', '사용자가입력한비밀번호')

검색

l.search_s('ou=user,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(검색대상속성이름=검색어)',
    ['결과속성1', '결과속성2' ..])
 
# array tuple.

검색 Scope

  • ldap.SCOPE_BASE

  • ldap.SCOPE_ONELEVEL

  • ldap.SCOPE_SUBTREE


# to be able to import ldap run pip install python-ldap
 
import ldap
 
if __name__ == "__main__":
ldap_server="x.x.x.x"
username = "someuser"
password= "somepassword"
# the following is the user_dn format provided by the ldap server
user_dn = "uid="+username+",ou=someou,dc=somedc,dc=local"
# adjust this to your base dn for searching
base_dn = "dc=somedc,dc=local"
connect = ldap.open(ldap_server)
search_filter = "uid="+username
try:
#if authentication successful, get the full user data
connect.bind_s(user_dn,password)
result = connect.search_s(base_dn,ldap.SCOPE_SUBTREE,search_filter)
# return all user data results
connect.unbind_s()
print result
except ldap.LDAPError:
connect.unbind_s()
print "authentication error"