mikecharles
7/28/2017 - 12:00 PM

Authenticate against LDAP in Python

Authenticate against LDAP in Python

#!/usr/bin/env python

import ldap
from getpass import getpass

# Set constants
HOST = '<HOST>'  # eg. ldaps://my-ldap-server.com
BASE_DN = '<BASE_DN>'  # eg. 'dc=example,dc=com'

# Set LDAP options
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

# Get username and password
username = input("Enter your Linux username: ")
password = getpass("Enter your Linux password: ")

# Set bind DN based on base DN
bind_DN = f'uid={username},{BASE_DN}'

# Initialize LDAP
l = ldap.initialize(HOST)

# Try to bind to the given username and password
try:
    l.simple_bind_s(bind_DN, password)
except ldap.NO_SUCH_OBJECT:
    print(f'Linux username {username} not found...')
    exit(1)
except ldap.UNWILLING_TO_PERFORM as e:
    if e.args[0]['info'] == 'Unauthenticated binds are not allowed':
        print('A password is required...')
    else:
        print('Something went wrong, please try again...')
    exit(1)
except ldap.INVALID_CREDENTIALS:
    print('Password incorrect...')
    exit(1)

# Perform a search for the given username's info
result = l.search_s(BASE_DN, ldap.SCOPE_SUBTREE, f'(uid={username})')