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

Merge branch 'multiple-groups' into 'master'

Add LDAP abstraction classes

See merge request core/python!9
parents d51be170 82f6425e
No related branches found
No related tags found
1 merge request!9Add LDAP abstraction classes
......@@ -2,26 +2,31 @@
import sys
import argparse
import collections
import lib_path
import lib
import tabulate
import dphysldap
OPTS = collections.OrderedDict()
OPTS['access'] = 'accessRight'
OPTS['blocked'] = 'blocked'
OPTS['home'] = 'homeDirectory'
OPTS['shell'] = 'loginShell'
OPTS['mail'] = 'mail'
OPTS['telephone'] = 'telephoneNumber'
def main():
parser = argparse.ArgumentParser(
add_help=False, description='Show group members')
parser.add_argument('group', help='The group name (cn)')
parser.add_argument('-a', '--access', dest='access',
action='store_const', const=True,
help='Show access rights column')
parser.add_argument('-b', '--blocked', dest='blocked',
action='store_const', const=True,
help='Show blocked column')
parser.add_argument('-m', '--mail', dest='mail',
action='store_const', const=True,
help='Show mail column')
parser.add_argument('-h', '--help',
action='help',
for k, v in OPTS.items():
parser.add_argument('-' + k[:1], '--' + k, dest=k,
action='store_const', const=True,
help='Show ' + v + ' column')
parser.add_argument('--help', action='help',
help='Show this help message and exit')
arg = vars(parser.parse_args())
......@@ -41,20 +46,17 @@ def main():
user_query = 'uid:' + ';'.join(members)
user_attrs = ['uid', 'uidNumber', 'gecos']
if arg['blocked']:
user_attrs.append('blocked')
if arg['access']:
user_attrs.append('accessRight')
if arg['mail']:
user_attrs.append('mail')
for k, v in OPTS.items():
if arg[k]:
user_attrs.append(v)
users = ldap.get_users(query=user_query, attributes=user_attrs)
if not users:
sys.exit('error: no users found')
cn = ','.join(group['cn'])
gid = ','.join([str(gid) for gid in group['gidNumber']])
cn = group['cn']
gid = group['gidNumber']
print('Members of {} ({}):'.format(cn, gid))
table = list()
......@@ -62,7 +64,7 @@ def main():
for u in users:
row = list()
for attr in user_attrs:
row.append(','.join([str(a) for a in u[attr]]))
row.append(u[attr])
table.append(row)
print(tabulate.tabulate(table, tablefmt='simple', headers=user_attrs))
......
#!/usr/bin/env python3
import ssl
from collections.abc import Mapping
import lib_path
import lib
import ldap3
......@@ -10,6 +11,46 @@ BASE = 'dc=phys,dc=ethz,dc=ch'
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):
"""
LDAP connection to random server in pool
......@@ -47,7 +88,7 @@ class Ldap(object):
"""
reader = ldap3.Reader(self.connection, obj, self.base, query, attributes)
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):
"""
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment