From eeadb2ce178320bc2832e17e2cbaf68f35c9b386 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josu=C3=A9=20Tille?= Date: Sat, 25 May 2019 23:50:59 +0200 Subject: [PATCH] Create a LDIF parser --- doc/ldap.rst | 14 ++++++++++++++ moulinette/utils/filesystem.py | 25 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/doc/ldap.rst b/doc/ldap.rst index ea459732..221b55da 100644 --- a/doc/ldap.rst +++ b/doc/ldap.rst @@ -372,3 +372,17 @@ Here how it looks like for domain and user: (:file:`None` ?) so you need to check it returns code. .. automethod:: moulinette.authenticators.ldap.Authenticator.remove + +Reading LDIF file +================= + +Reading parsing a ldif to be able to insert in the LDAP database is really easy. Here is how to get the content of a LDIF file + +:: + + from moulinette.utils.filesystem import read_ldif + + my_reslut = read_ldif("your_file.ldif") + + +Note that the main difference of what the auth object return with the search method is that this function return a 2-tuples with the "dn" and the LDAP entry. diff --git a/moulinette/utils/filesystem.py b/moulinette/utils/filesystem.py index 521f93c5..e981d94f 100644 --- a/moulinette/utils/filesystem.py +++ b/moulinette/utils/filesystem.py @@ -77,6 +77,31 @@ def read_yaml(file_path): return loaded_yaml +def read_ldif(file_path): + """ + Safely read a LDIF file and create struct in the same style than + what return the auth objet with the seach method + The main difference with the auth object is that this function return a 2-tuples + with the "dn" and the LDAP entry. + + Keyword argument: + file_path -- Path to the ldif file + """ + from ldif import LDIFRecordList + + # Open file and read content + try: + with open(file_path, "r") as f: + parser = LDIFRecordList(f) + parser.parse() + except IOError as e: + raise MoulinetteError('cannot_open_file', file=file_path, error=str(e)) + except Exception as e: + raise MoulinetteError('error_reading_file', file=file_path, error=str(e)) + + return parser.all_records + + def write_to_file(file_path, data, file_mode="w"): """ Write a single string or a list of string to a text file.