Created
July 28, 2017 12:00
-
-
Save mikecharles/2c07281811484cd81dabb6facaaeacc5 to your computer and use it in GitHub Desktop.
Authenticate against LDAP in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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})') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment