Skip to content
Snippets Groups Projects
Commit 2513b954 authored by Sven Mäder's avatar Sven Mäder :speech_balloon:
Browse files

Add LDAP abstraction classes

parent d51be170
No related branches found
No related tags found
1 merge request!9Add LDAP abstraction classes
...@@ -53,8 +53,8 @@ def main(): ...@@ -53,8 +53,8 @@ def main():
if not users: if not users:
sys.exit('error: no users found') sys.exit('error: no users found')
cn = ','.join(group['cn']) cn = group['cn']
gid = ','.join([str(gid) for gid in group['gidNumber']]) gid = group['gidNumber']
print('Members of {} ({}):'.format(cn, gid)) print('Members of {} ({}):'.format(cn, gid))
table = list() table = list()
...@@ -62,7 +62,7 @@ def main(): ...@@ -62,7 +62,7 @@ def main():
for u in users: for u in users:
row = list() row = list()
for attr in user_attrs: for attr in user_attrs:
row.append(','.join([str(a) for a in u[attr]])) row.append(u[attr])
table.append(row) table.append(row)
print(tabulate.tabulate(table, tablefmt='simple', headers=user_attrs)) print(tabulate.tabulate(table, tablefmt='simple', headers=user_attrs))
......
#!/usr/bin/env python3 #!/usr/bin/env python3
import ssl import ssl
from collections.abc import Mapping
import lib_path import lib_path
import lib import lib
import ldap3 import ldap3
...@@ -10,6 +11,46 @@ BASE = 'dc=phys,dc=ethz,dc=ch' ...@@ -10,6 +11,46 @@ BASE = 'dc=phys,dc=ethz,dc=ch'
CA_CERTS = '/etc/ssl/certs/ca-certificates.crt' CA_CERTS = '/etc/ssl/certs/ca-certificates.crt'
class AttributeValue(list):
"""
Abstraction class for LDAP attribute values imitating list
"""
def __str__(self):
"""
Modifies the "informal" string value of str(x) or print(x)
"""
return self.get_str()
def get_str(self, delimit=','):
"""
Returns a string representation of all values
"""
return delimit.join([str(e) for e in self])
class Entry(Mapping):
"""
Abstraction class for LDAP Entry imitating dict
"""
def __init__(self, *args, **kwargs):
self._dict = dict(*args, **kwargs)
def __getitem__(self, key):
"""
If value is a list, convert it to AttributeValue
"""
value = self._dict[key]
if isinstance(value, list):
return AttributeValue(value)
return value
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._storage)
class Ldap(object): class Ldap(object):
""" """
LDAP connection to random server in pool LDAP connection to random server in pool
...@@ -47,7 +88,7 @@ class Ldap(object): ...@@ -47,7 +88,7 @@ class Ldap(object):
""" """
reader = ldap3.Reader(self.connection, obj, self.base, query, attributes) reader = ldap3.Reader(self.connection, obj, self.base, query, attributes)
reader.search() reader.search()
return [e.entry_attributes_as_dict for e in reader.entries] return [Entry(e.entry_attributes_as_dict) for e in reader.entries]
def get_users(self, query='', attributes=None): def get_users(self, query='', attributes=None):
""" """
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment