66 lines
2.1 KiB
Python
66 lines
2.1 KiB
Python
from helpers import *
|
|
|
|
class LDAPCore:
|
|
def __init__(self, root_cred, domain):
|
|
self.domain = domain
|
|
self.dn = self.__domain_to_dn()
|
|
if root_cred:
|
|
self.root_name = root_cred[0]
|
|
self.root_pswd = root_cred[1]
|
|
self.root_user = "cn=%s,%s" % (self.root_name, self.dn)
|
|
self.connection = ldap_connect(self)
|
|
else:
|
|
self.connection = ldap_connect(self, anonymous=True)
|
|
|
|
def __domain_to_dn(self, domain=None):
|
|
if domain is None:
|
|
domain = self.domain
|
|
prefix = lambda p: "dc=%s" % p
|
|
dcs = list(map(prefix, domain.split(".")))
|
|
return ",".join(dcs)
|
|
|
|
def close(self):
|
|
quit(self.connection)
|
|
|
|
def search(self, find="", ou="", attrs=[], search_dn="",
|
|
search="(objectclass=*)", root=False):
|
|
return ldap_search(self, find, ou, attrs, search_dn, search, root)
|
|
|
|
def parse_passwd(self, user_info):
|
|
uid = user_info["uid"]
|
|
uidn = user_info["uidNumber"]
|
|
gidn = user_info["gidNumber"]
|
|
gecos = user_info["gecos"]
|
|
home = user_info["homeDirectory"]
|
|
shell = user_info["loginShell"]
|
|
return "%s:x:%s:%s:%s:%s:%s" % (uid, uidn, gidn, gecos, home, shell)
|
|
|
|
def parse_group(self, group_info):
|
|
cn = group_info["cn"]
|
|
gidn = group_info["gidNumber"]
|
|
return "%s:x:%s:" % (cn, gidn)
|
|
|
|
def users(self):
|
|
ldap_users = "ou=People,%s" % self.dn
|
|
attrs = [
|
|
"uid",
|
|
"uidNumber",
|
|
"gidNumber",
|
|
"gecos",
|
|
"homeDirectory",
|
|
"loginShell"
|
|
]
|
|
results = self.search(search_dn=ldap_users, attrs=attrs)
|
|
users = [self.parse_passwd({
|
|
k: v[0] for k, v in user[1].items()
|
|
}) for user in results if len(user[1]) > 0]
|
|
return users
|
|
|
|
def groups(self):
|
|
ldap_users = "ou=Group,%s" % self.dn
|
|
results = self.search(search_dn=ldap_users, attrs=["cn","gidNumber"])
|
|
groups = [self.parse_group({
|
|
k: v[0] for k, v in group[1].items()
|
|
}) for group in results if len(group[1]) > 0]
|
|
return groups
|