Syncing LDAP users with Django

I recently wrote about configuring a Django application to auth against an LDAP Server using django-auth-ldap. Under this configuration, the first time a user logs in using LDAP, their Django account gets created, and you can then treat them like a standard Django user.

However, in some cases you may wish to be able to refer to a user without them ever having logged in. In order to achieve this, I wrote a basic Django management script that queries an LDAP server and filters users by job title (since I only wanted to import certain users), and then creates the user appropriately:

In the above example, the script is set up to only import users with "Research Student" in the employeeType field using an LDAP Search Filter.

This script can be run nightly using cron (or managed cron, using something like django-kronos), or manually as and when required by running python manage.py sync_ldap.

In addition to the filtered sync script, as I occasionally needed to import users outside of this employeeType, I wrote a script to manually add a user with a given username:

This script can be executed by running: python manage.py add_user username1 username2 username3, where username1, username2, username3, are the usernames of the LDAP users you wish to import.