Python

[Python] ldap3 사용법

비번변경 2024. 1. 5. 17:07

개요

보통 회사에서는 계정 관리, 인증 등에 LDAP을 사용하고 있는데, LDAP 서버에 저장된 정보 조회가 필요한 상황이다. Python으로 LDAP 서버에 요청할 수 있는 ldap3 라이브러리 사용방법을 간단히 적어둔다.

 

ldap3는 간단히 server, connection 객체를 정의하고, 연결에 대해 명령을 실행하는 방식으로 사용한다.

 

 

ldap3 라이브러리 설치

pip 등을 이용해 설치할 수 있다.

pip install ldap3

 

 

ldap3 import

ldap3에서 제공하는 클래스 등을 활용하기 위해 import 하여 사용한다. 보통 아래와 같이 사용하는 것 같다.

from ldap3 import Server, Connection, ALL

 

 

서버 접근

Ldap 서버에 접근할 때는 접근할 서버의 주소로 Server 객체를 생성 후, Connection 객체를 생성한다.

address = 'ip'
address = 'url'
address = 'ldap://ip'
address = 'ldaps://ip'

server = Server(address, get_info=ALL)
connection = Connection(server, auto_bind=True)

서버에서 정보를 가져와야 할 때는 Server 객체 생성 시 가져올 정보를 get_info 매개변수로 지정한다. 가져온 정보는 .info 속성으로 확인할 수 있다.

Connection을 생성하면서 바인딩 작업을 하고 싶다면 Connection 객체 생성 시 auto_bind 매개변수를 True로 지정한다. 

 

참고로, ldaps를 사용하기 위해서는 인증서가 설치되어 있어야 한다.

 

 

서버 로그인

서버에 계정정보를 제공하여 연결하고 싶다면, Connection 객체를 생성할 때 사용자명과 비밀번호 같은 인증 정보를 전달한다.

server = Server(address, get_info=ALL)
connection = Connection(server, user=user_id, password=password, auto_bind=True)

 

 

정보 검색

ldap은 주로 저장된 데이터를 검색하는 경우가 많다. 데이터를 검색할 때는 Connection.search 함수를 사용한다.

search 함수를 사용할 때는 검색을 시작할 위치를 지정하는 search_base, 검색 기준인 search_filter 매개변수를 전달한다.

from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES

base = 'ou=kakao,dc=tistory,dc=net'
filter = "(cn={})".format(user_id)
attributes = ldap3.ALL_ATTRIBUTES

connection.search(base, filter, attributes=attributes)
print(connection.entries)

조회된 결과는 Connection.entries 속성으로 확인할 수 있다. 조회한 결과는 entry_attributes_as_dict 함수를 이용해 Dictionary로 변환할 수도 있다.

print([entry.entry_attributes_as_dict for entry in connection.entries])

 

 

참고 문서

https://ldap3.readthedocs.io/en/latest/tutorial_intro.html

https://ldap3.readthedocs.io/en/latest/tutorial_searches.html

 

728x90