ldap-users/lib/helpers.py

58 lines
1.9 KiB
Python

from __future__ import print_function
from sys import stderr
from getpass import getpass
from ldap import initialize, LDAPError, INVALID_CREDENTIALS, SCOPE_SUBTREE
def eprint(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def quit(con=None):
if con:
con.unbind_s()
def ldap_connect(core, anonymous=False):
ldap_host = core.domain
root_user = getattr(core, "root_user", None)
root_pswd = getattr(core, "root_pswd", None)
if not anonymous:
print("Attempting to connect to LDAP...")
if root_pswd is None:
root_pswd = getpass("Password for %s: " % root_user)
try:
con = initialize("ldap://%s" % ldap_host)
try:
if not anonymous:
con.simple_bind_s(root_user, root_pswd)
else:
con.simple_bind_s()
except INVALID_CREDENTIALS:
eprint("Username or password is wrong, or anonymous is disabled")
quit(con)
except LDAPError, e:
if type(e.message) == dict and e.message.has_key("desc"):
eprint("Error: %s" % e.message["desc"])
else:
eprint(e)
quit(con)
return con
except LDAPError, e:
if type(e.message) == dict and e.message.has_key("desc"):
eprint(e.message["desc"])
else:
eprint(e)
quit(con)
def ldap_search(core, find="", ou="", attrs=[], search_dn="",
search="(objectclass=*)", root=False):
con = core.connection
if not len(search_dn) > 0:
search_dn = "%s" % core.dn
if len(ou) > 0 and len(find) > 0:
search_dn = "%s,ou=%s,%s" % (find, ou, search_dn)
elif len(ou) > 0 and len(find) == 0:
search_dn = "ou=%s,%s" % (ou, search_dn)
elif len(ou) == 0 and len(find) > 0:
search_dn = "%s,%s" % (find, search_dn)
return con.search_s(search_dn, SCOPE_SUBTREE, search, attrs)