How to Import Users from CSV into LDAP-like Dicts in Python
Reads a CSV of user records and converts each row into an LDAP-style dictionary with standard attributes using Python's csv module.
Python code
40 linesimport csv
import io
from pathlib import Path
def mock_ldap_import(csv_path):
"""
Reads a CSV file with user data and returns a list of LDAP-like user dicts.
Adds standard LDAP attributes that would come from directory schema.
"""
with open(csv_path, newline="", encoding="utf-8") as csvfile:
reader = csv.DictReader(csvfile)
users = []
for row in reader:
user = {
"uid": row["username"],
"cn": f"{row['first_name']} {row['last_name']}",
"mail": row["email"],
"givenName": row["first_name"],
"sn": row["last_name"],
"department": row.get("department", "unknown"),
"objectClass": ["inetOrgPerson", "organizationalPerson"],
"enabled": row.get("enabled", "TRUE").upper() == "TRUE",
}
users.append(user)
return users
if __name__ == "__main__":
sample_csv = """username,first_name,last_name,email,department,enabled
jdoe,John,Doe,jdoe@example.com,Engineering,TRUE
asmith,Alice,Smith,asmith@example.com,Sales,TRUE
bmarley,Bob,Marley,bmarley@example.com,,FALSE
"""
p = Path("/tmp/mock_users.csv")
p.write_text(sample_csv)
imported_users = mock_ldap_import(p)
for user in imported_users:
print(user)
Output
{'uid': 'jdoe', 'cn': 'John Doe', 'mail': 'jdoe@example.com', 'givenName': 'John', 'sn': 'Doe', 'department': 'Engineering', 'objectClass': ['inetOrgPerson', 'organizationalPerson'], 'enabled': True}
{'uid': 'asmith', 'cn': 'Alice Smith', 'mail': 'asmith@example.com', 'givenName': 'Alice', 'sn': 'Smith', 'department': 'Sales', 'objectClass': ['inetOrgPerson', 'organizationalPerson'], 'enabled': True}
{'uid': 'bmarley', 'cn': 'Bob Marley', 'mail': 'bmarley@example.com', 'givenName': 'Bob', 'sn': 'Marley', 'department': 'unknown', 'objectClass': ['inetOrgPerson', 'organizationalPerson'], 'enabled': False}
How it works
The csv.DictReader reads each row as a dictionary keyed by the header row, making it easy to map columns to LDAP attribute names like uid and cn. The get() method supplies a default value for missing columns (e.g., department defaults to 'unknown'), so the script won't crash if a field is omitted. The enabled flag is normalized to a boolean by comparing the uppercase value against 'TRUE', which handles common variants like 'true' or 'False'. Finally, objectClass is set as a list to represent multi-valued LDAP attributes.
Common mistakes
- Calling `row["department"]` directly without `.get()` when the column may be missing or empty.
- Forgetting to convert the CSV's `enabled` field from string to boolean, leading to incorrect logic.
- Assuming `csv.DictReader` preserves column order, which it does not; access fields by name instead of index.
- Opening the file without `newline="` (or not using `encoding="utf-8"`) on Windows, causing `\r` in field values.
Variations
- Use `pandas.read_csv` to load the CSV into a DataFrame, then convert rows to dicts with `df.to_dict('records')`.
- Write the parsed users to an actual LDIF file using `ldap3` for a real LDAP import.
- Use `csv.DictWriter` to write a cleaned CSV that includes only valid LDAP attributes.
Real-world use cases
- Bulk-provisioning user accounts in a test LDAP server from an HR export in CSV format.
- Migrating on-premises user data to a cloud directory service by transforming rows into LDAP-compatible schemas.
- In a DevOps pipeline, importing team members from a spreadsheet into a sandbox directory for integration tests.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.