Skip to content

Instantly share code, notes, and snippets.

@rechner
Created November 18, 2019 23:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rechner/57c123d243b8adb83ccb1dc94c80847f to your computer and use it in GitHub Desktop.
Save rechner/57c123d243b8adb83ccb1dc94c80847f to your computer and use it in GitHub Desktop.
LDAP Auth script for HomeAssistant
import os
from ldap3 import Server, Connection, ALL, core
# XXX: Update these with settings apropriate to your environment:
# (I use FreeIPA and an homeassistant group assignment)
SERVER = "ipa.example.com"
USERDN = "uid={},cn=users,cn=accounts,dc=example,dc=com"
TIMEOUT = 3
BASEDN = USERDN
SCOPE = "base"
FILTER = "(&(objectClass=person)(memberOf=cn=homeassistant,cn=groups,cn=accounts,dc=example,dc=com))"
ATTRS = ""
if 'username' not in os.environ and 'password' not in os.environ:
print("Need username and password environment variables!")
exit()
USERDN = USERDN.format(os.environ['username'])
BASEDN = BASEDN.format(os.environ['username'])
server = Server(SERVER, get_info=ALL)
try:
conn = Connection(server, USERDN, password=os.environ['password'], auto_bind=True)
print("whoami: {}".format(conn.extend.standard.who_am_i()))
search = conn.search(BASEDN, FILTER)
if search:
print("Search success: {}".format(conn.entries))
exit(0)
else:
print("LDAP bind succeded, but search yielded empty result")
exit(1)
except core.exceptions.LDAPBindError as e:
print(e)
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment