univention package

Contents

univention package#

Subpackages#

Submodules#

univention.config_registry_info module#

class univention.config_registry_info.Variable(registered: bool = True)[source]#

Bases: LocalizedDictionary

UCR variable description.

check() list[str][source]#

Check description for completeness.

Returns:

List of missing settings.

class univention.config_registry_info.Category[source]#

Bases: LocalizedDictionary

UCR category description.

check() list[str][source]#

Check description for completeness.

Returns:

List of missing settings.

class univention.config_registry_info.ConfigRegistryInfo(install_mode: bool = False, registered_only: bool = True, load_customized: bool = True)[source]#

Bases: object

UCR variable and category descriptions.

Initialize variable and category descriptions.

Parameters:
  • install_modeTrue deactivates the use of an UCR instance.

  • registered_onlyFalse creates synthetic entries for all undescribed but set variables.

  • load_customizedFalse deactivates loading customized descriptions.

BASE_DIR = '/etc/univention/registry.info'#
CATEGORIES = 'categories'#
VARIABLES = 'variables'#
CUSTOMIZED = '_customized'#
FILE_SUFFIX = '.cfg'#
check_categories() dict[str, list[str]][source]#

Check all categories for completeness.

Returns:

dictionary of incomplete category descriptions.

check_variables() dict[str, list[str]][source]#

Check variables.

Returns:

dictionary of incomplete variable descriptions.

read_categories(filename: str) None[source]#

Load a single category description file.

Parameters:

filename – File to load.

load_categories() None[source]#

Load all category description files.

check_patterns() None[source]#

Match descriptions agains currently defined UCR variables.

describe_search_term(term: str) dict[str, Variable][source]#

Try to apply a description to a search term.

This is not complete, because it would require a complete “intersect two regular languages” algorithm.

Parameters:

term – Search term.

Returns:

Dictionary mapping variable pattern to Variable info blocks.

write_customized() None[source]#

Persist the customized variable descriptions.

read_customized() None[source]#

Read customized variable descriptions.

read_variables(filename: str | None = None, package: str | None = None, override: bool = False) None[source]#

Read variable descriptions.

Parameters:
  • filename – Explicit filename for loading.

  • package – Explicit package name.

  • overrideTrue to overwrite already loaded descriptions.

Raises:

AttributeError – if neither filename nor package are given.

get_categories() Iterable[str][source]#

Return a list of category names.

Returns:

List if categories.

get_category(name: str) Category | None[source]#

Returns a category object associated with the given name or None.

Parameters:

name – Name of the category.

Returns:

get_variables(category: str | None = None) dict[str, Variable][source]#

Return dictionary of variable info blocks belonging to given category.

Parameters:

category – Name of the category. None defaults to all variables.

Returns:

Dictionary mapping variable-name to Variable instance.

get_variable(key: str) Variable | None[source]#

Return the description of a variable.

Parameters:

key – Variable name.

Returns:

description object or None.

add_variable(key: str, variable: Variable) None[source]#

Add a new variable information item or overrides an old entry.

Parameters:
  • key – Variable name.

  • variableVariable instance.

match_pattern(key: str) Variable | None[source]#

Searches the variable info, whichs regex pattern patches the given key.

Parameters:

key – search key which should be matched by the regex pattern

Returns:

corresponding variable info block

univention.config_registry_info.set_language(lang: str) None[source]#

Set the default language.

univention.debhelper module#

Debhelper compatible routines.

univention.debhelper.doIt(*argv: str) int[source]#

Execute argv and wait.

Parameters:

argv – List of command and arguments.

>>> doIt('true')
0
univention.debhelper.binary_packages() list[str][source]#

Get list of binary packages from debian/control file.

>>> binary_packages()
[...]
univention.debhelper.parseRfc822(f: str) list[dict[str, list[str]]][source]#

Parses string f as a RFC 822 conforming file and returns list of sections, each a dict mapping keys to lists of values. Splits file into multiple sections separated by blank line.

Parameters:

f – The messate to parse.

Returns:

A list of dictionaries.

Note

For real Debian files, use the debian.deb822 module from the python-debian package.

>>> res = parseRfc822('Type: file\nFile: /etc/fstab\n\nType: Script\nScript: /bin/false\n')
>>> res == [{'Type': ['file'], 'File': ['/etc/fstab']}, {'Type': ['Script'], 'Script': ['/bin/false']}]
True
>>> parseRfc822('')
[]
>>> parseRfc822('\n')
[]
>>> parseRfc822('\n\n')
[]
univention.debhelper.parser_dh_sequence(parser: ArgumentParser, argv: Sequence[str] | None = None) Namespace[source]#

Add common argument for Debian helper sequence.

Parameters:

parser – argument parser

Returns:

parsed arguments

>>> parser = ArgumentParser()
>>> args = parser_dh_sequence(parser, ["-v"])
>>> args.verbose
True

univention.debug module#

Univention debugging and logging library.

example:

>>> f = init('stdout', NO_FLUSH, FUNCTION)
... ...  DEBUG_INIT
>>> set_level(LISTENER, ERROR)
univention.debug.begin()#

begin(fname) - Function starts here.

Log the begin of function ‘fname’. fname - name of the function starting.

univention.debug.debug(category, level, message, utf8=True)[source]#

Log message ‘message’ of severity ‘level’ to facility ‘category’.

Parameters:
  • category (int) – ID of the category, e.g. MAIN, LDAP, USERS, …

  • level (int) – Level of logging, e.g. ERROR, WARN, PROCESS, INFO, ALL

  • message (str) – The message to log.

  • utf8 (bool) – Assume the message is UTF-8 encoded.

>>> debug(LISTENER, ERROR, 'Fatal error: var=%s' % 42)
... ...  LISTENER    ( ERROR   ) : Fatal error: var=42
univention.debug.end()#

end(fname) - Function ends here.

Log the end of function ‘fname’. fname - name of the function ending.

univention.debug.exit()#

exit() - Close debug log.

Close the debug logfile.

class univention.debug.function(fname, utf8=True)[source]#

Bases: object

Log function call begin and end.

Parameters:
  • fname (str) – name of the function starting.

  • utf8 (bool) – Assume the message is UTF-8 encoded.

Deprecated since version 4.4: Use function decorator trace() instead.

>>> def my_func(agr1, agr2=None):
...    _d = function('my_func(...)')  # noqa: F841
...    return 'yes'
>>> my_func(42)
'yes'
univention.debug.get_level(category) int - Get debug level for category.#

Get minimum required severity for facility ‘category’. category - ID of the category, e.g. MAIN, LDAP, USERS, …

univention.debug.init()#

init(logfile, force_flush, trace_function, structured) - Initialize debugging library.

Initialize debugging library for logging to ‘logfile’. logfile - name of the logfile, or ‘stderr’, or ‘stdout’. force_flush - force flushing of messages (True). trace_function - enable (True) or disable (False) function tracing. structured - enable (True) or disable (False) structured logging.

univention.debug.reopen()#

reopen() - Re-open logfile.

Close and re-open the debug logfile.

univention.debug.set_function()#

set_function(activate) - Enable function tracing.

Enable or disable the logging of function begins and ends. activate - enable (True) or disable (False) function tracing.

univention.debug.set_level()#

set_level(category, level) - Set debug level for category.

Set minimum required severity ‘level’ for facility ‘category’. category - ID of the category, e.g. MAIN, LDAP, USERS, … level - Level of logging, e.g. ERROR, WARN, PROCESS, INFO, ALL

univention.debug.set_structured()#

set_structured(activate) - Define weather to use structured logging formats.

activate - enable (True) or disable (False) structured logging format..

univention.debug.trace(with_args=True, with_return=False, repr=<slot wrapper '__repr__' of 'object' objects>)[source]#

Log function call, optional with arguments and result.

Parameters:
  • with_args (bool) – Log function arguments.

  • with_return (bool) – Log function result.

  • repr – Function accepting a single object and returing a string representation for the given object. Defaults to object.__repr__(), alternative repr().

>>> @trace(with_args=True, with_return=True)
... def my_func(arg1, arg2=None):
...     return 'yes'
>>> my_func(42)
'yes'
>>> class MyClass(object):
...     @trace(with_args=True, with_return=True, repr=repr)
...     def my_meth(self, arg1, arg2=None):
...         return 'yes'
>>> MyClass().my_meth(42)
'yes'
>>> @trace()
... def my_bug():
...     1 / 0
>>> my_bug()
Traceback (most recent call last):
    ...
ZeroDivisionError: integer division or modulo by zero

univention.debug2 module#

Python native Univention debugging library.

See univention.debug for an alternative being a wrapper for the C implementation.

univention.debug2.init(logfile, force_flush=0, enable_function=0, enable_syslog=0)[source]#

Initialize debugging library for logging to ‘logfile’.

Parameters:
  • logfile (str) – name of the logfile, or ‘stderr’, or ‘stdout’.

  • force_flush (bool) – force flushing of messages (True).

  • trace_function (bool) – enable (True) or disable (False) function tracing.

  • enable_syslog (bool) – enable (True) or disable (False) logging to SysLog.

Returns:

output file or None.

univention.debug2.exit()[source]#

Close debug logfile.

univention.debug2.reopen()[source]#

Close and re-open the debug logfile.

univention.debug2.set_level(category, level)[source]#

Set minimum required severity ‘level’ for facility ‘category’.

Parameters:
  • category (int) – ID of the category, e.g. MAIN, LDAP, USERS, …

  • level (int) – Level of logging, e.g. ERROR, WARN, PROCESS, INFO, ALL, TRACE

univention.debug2.get_level(category)[source]#

Get minimum required severity for facility ‘category’.

Parameters:

category (int) – ID of the category, e.g. MAIN, LDAP, USERS, …

Returns:

Return debug level of category.

Return type:

int

univention.debug2.set_function(activate)[source]#

Enable or disable the logging of function begins and ends.

Parameters:

activate (bool) – enable (True) or disable (False) function tracing.

Deprecated since version 4.4: Use function decorator trace() instead.

univention.debug2.debug(category, level, message, utf8=True)[source]#

Log message ‘message’ of severity ‘level’ to facility ‘category’.

Parameters:
  • category (int) – ID of the category, e.g. MAIN, LDAP, USERS, …

  • level (int) – Level of logging, e.g. ERROR, WARN, PROCESS, INFO, ALL, TRACE

  • message (str) – The message to log.

  • utf8 (bool) – Assume the message is UTF-8 encoded.

class univention.debug2.function(fname, utf8=True)[source]#

Bases: object

Log function call begin and end.

Parameters:
  • fname (str) – name of the function starting.

  • utf8 (bool) – Assume the message is UTF-8 encoded.

Deprecated since version 4.4: Use function decorator trace() instead.

>>> def my_func(agr1, agr2=None):
...    _d = function('my_func(...)')  # noqa: F841
...    return 'yes'
>>> my_func(42)
'yes'
univention.debug2.set_structured(use_structured=False)[source]#
univention.debug2.trace(with_args=True, with_return=False, repr=<slot wrapper '__repr__' of 'object' objects>)[source]#

Log function call, optional with arguments and result.

Parameters:
  • with_args (bool) – Log function arguments.

  • with_return (bool) – Log function result.

  • repr – Function accepting a single object and returing a string representation for the given object. Defaults to object.__repr__(), alternative repr().

>>> @trace(with_args=True, with_return=True)
... def my_func(arg1, arg2=None):
...     return 'yes'
>>> my_func(42)
'yes'
>>> class MyClass(object):
...     @trace(with_args=True, with_return=True, repr=repr)
...     def my_meth(self, arg1, arg2=None):
...         return 'yes'
>>> MyClass().my_meth(42)
'yes'
>>> @trace()
... def my_bug():
...     1 / 0
>>> my_bug()
Traceback (most recent call last):
    ...
ZeroDivisionError: integer division or modulo by zero

univention.dn module#

A convenient wrapper to easily work with LDAP Distinguished Names (DNs)

class univention.dn.DN(dn: str)[source]#

Bases: object

A LDAP Distinguished Name.

dn#
property rdn: Self#
>>> DN('foo=1,bar=2').rdn
('foo', '1')
property parent: Self | None#
>>> DN('foo=1,bar=2').parent == DN('bar=2')
True
endswith(other: str | Self)[source]#
>>> DN('foo=1,bar=2').endswith('bar=2')
True
>>> DN('foo=1,bar=2').endswith('foo=1')
False
startswith(other: str | Self)[source]#
>>> DN('foo=1,bar=2').startswith('foo=1')
True
>>> DN('foo=1,bar=2').startswith('bar=2')
False
walk(base)[source]#
>>> [str(x) for x in DN('foo=1,bar=2,baz=3,blub=4').walk('baz=3,blub=4')]
['baz=3,blub=4', 'bar=2,baz=3,blub=4', 'foo=1,bar=2,baz=3,blub=4']
classmethod set(values: list[str]) set[Self][source]#

Returns a unique set of DNs.

>>> len(DN.set(['CN=computers,dc=foo', 'cn=computers,dc=foo', 'cn = computers,dc=foo', 'CN=Computers,dc=foo']))
1
classmethod values(dns: list[Self]) set[str][source]#

Return a unique set of DN strings from DNs.

>>> DN.values(DN.set(['cn=foo', 'cn=bar']) - DN.set(['cn = foo'])) == {'cn=bar'}
True

univention.info_tools module#

class univention.info_tools.LocalizedValue(*args, **kwargs)[source]#

Bases: dict

Localized description entry.

get(locale: str | None = None) str[source]#

Return the value for key if key is in the dictionary, else default.

set(value: str, locale: str | None = None) None[source]#
set_default(default: str) None[source]#
get_default() str[source]#
class univention.info_tools.LocalizedDictionary[source]#

Bases: dict

Localized descriptions.

get(key: str) str | None[source]#
get(key: str, default: _VT) str | _VT

Return the value for key if key is in the dictionary, else default.

has_key(key: str) bool#

True if the dictionary has the specified key, else False.

normalize(key: str | None = None) dict[str, str][source]#
get_dict(key: str) dict[str, str][source]#
class univention.info_tools.UnicodeConfig[source]#

Bases: ConfigParser

read(filename, encoding='UTF-8')[source]#

Read and parse a filename or an iterable of filenames.

Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential configuration file locations (e.g. current directory, user’s home directory, systemwide directory), and all existing configuration files in the iterable will be read. A single filename may also be given.

Return list of successfully read files.

write(fp)[source]#

Write an .ini-format representation of the configuration state.

univention.info_tools.set_language(lang)[source]#

univention.ldif module#

Univention LDIF tool

univention.ldif.ldif_decode(src: ~typing.IO[str] = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>, dst: ~typing.IO[bytes] = <_io.BufferedWriter name='<stdout>'>) None[source]#

Decode bas64 in LDIF.

univention.ldif.ldif_normalize(src: ~typing.IO[str] = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>, dst: ~typing.IO[bytes] = <_io.BufferedWriter name='<stdout>'>) None[source]#

Unwrap and base64 decode LDIF.

univention.ldif.ldif_unwrap(src: ~typing.IO[str] = <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>, dst: ~typing.IO[bytes] = <_io.BufferedWriter name='<stdout>'>) None[source]#

Unwrap LDIF.

univention.logging module#

A python-logging interface compatible wrapper for logging with univention.debug

>>> import univention.logging
>>> import logging
>>> logger = logging.getLogger('MAIN').getChild(__name__)
>>> univention.logging.basicConfig(level=logging.INFO)
>>> logger.info('test')
class univention.logging.DebugHandler(category=0, level=0, auto_init=False, delay_init=False, do_exit=True, filename='stderr')[source]#

Bases: Handler

A logging handler which logs to univention.debug

Initializes the instance - basically setting the formatter to None and the filter list to empty.

emit(record)[source]#

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

init(filename='stderr', flush=0, function=0, structured=False)[source]#

Initialize univention.debug. Must only be called once. returns the file descriptor on success

reopen()[source]#

reopen the univention.debug logfile. must be called e.g. after log rotation.

close()[source]#

Tidy up any resources used by the handler.

This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.

get_ud_level()[source]#
set_structured(use_structured_logging)[source]#
getLevel()[source]#
setLevel(level)[source]#

Set the logging level of this handler. level must be an int or a str.

class univention.logging.LevelDependentFormatter(datefmt=None, log_pid=False)[source]#

Bases: Formatter

A formatter which logs different formats depending on the log level.

Deprecated since version 5.2-3: unstructured logging with different formats will be removed in UCS 5.2-5.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

RESERVED = ('args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'levelname', 'levelno', 'lineno', 'message', 'module', 'msecs', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'stack_info', 'taskName', 'thread', 'threadName', 'prefix', 'request_id', 'pid', 'umcmodule')#
setFormat(level, fmt)[source]#
format(record)[source]#

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

class univention.logging.Logger(name, level=0, log_pid=False, **kwargs)[source]#

Bases: Logger

A logger which automatically adds univention.debug as logging handler.

Can be set as global default logger via logging.setLoggerClass(univention.logging.Logger).

Initialize the logger with a name and an optional level.

setLevel(level)[source]#

Set the logging level of this logger. level must be an int or a str.

isEnabledFor(level)[source]#

Is this logger enabled for level ‘level’?

getEffectiveLevel()[source]#

Get the effective level for this logger.

Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found.

set_log_pid(log_pid)[source]#
set_ud_level(level)[source]#
init(filename='stderr', flush=0, function=0, structured=False)[source]#

init univention.debug. must only be called once. returns the file descriptor on success

exit()[source]#
reopen()[source]#

reopen the univention.debug logfile. must be called e.g. after log rotation.

set_structured(use_structured_logging)[source]#
destroy()[source]#
class univention.logging.StructuredFormatter(fmt=None, *, defaults=None, data_fields=None, data_mapping=None, data_defaults=None, data_ignored_keys=None, add_full_tracebacks=True, with_date_prefix=False, key='logfmt')[source]#

Bases: Formatter

A formatter combining prefixed content and structured data from logfmt.

Producing log lines like:

2025-01-01T00:00:00.000000+00:00 INFO [ -] module.function:1 the messaget| pid=12345 logname=ADMIN

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

formatMessage(record)[source]#
format(record)[source]#

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

formatTime(record, datefmt=None)[source]#

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

univention.logging.basicConfig(filename='stdout', level=None, *, univention_debug_level=None, log_pid=False, univention_debug_flush=1, univention_debug_function=0, univention_debug_categories=None, do_exit=True, delay_init=False, use_structured_logging=False, **kwargs)[source]#

Do basic configuration for the logging system. Especially initialize the logging module so that it uses univention.debug:

>>> import logging
>>> basicConfig(level=logging.DEBUG)
>>> logger = logging.getLogger('ADMIN').getChild(__name__)
>>> logger.info('some info')
univention.logging.extendLogger(name: str, **kwargs: Any) None[source]#

Ensure that the logger with the specified name is a univention-debug logger otherwise transform it.

Parameters:
  • name – The name of the logger.

  • univention_debug_category – A univention.debug category (if not given name will be used). If the logger name should differ from the univention-debug category this param can be used as initialization call to create the logger once.

>>> import logging
>>> logger = logging.getLogger('myservice')
>>> extendLogger('myservice', univention_debug_category='MAIN')
>>> logger.init('stdout', ud.FLUSH, ud.NO_FUNCTION)
>>> logger.setLevel(logging.WARNING)
>>> logger.warning('some warning')
univention.logging.getLogger(name: str, **kwargs: Any) Logger[source]#

Return a logger with the specified name, creating it if necessary.

Parameters:
  • name – The name of a univention.debug category (if not existant ud.MAIN will be used)

  • extend – Whether a non univention-debug logger should be extended to be one.

  • univention_debug_category – If the logger name should differ from the univention-debug category this param can be used as initialization call to create the logger once.

Warning

If a logger with that name already exists and is not a univention.logging.Logger no univention-debug logger is initialized and returned.

>>> logger = getLogger('ADMIN')  # .getChild(__name__)
>>> logger.init('stdout', ud.FLUSH, ud.NO_FUNCTION)
>>> logger.setLevel(logging.WARNING)
>>> logger.info('some info')
>>> logger.error('some error')
class univention.logging.BufferingFormatter(linefmt=None)[source]#

Bases: object

A formatter suitable for formatting a number of records.

Optionally specify a formatter which will be used to format each individual record.

format(records)[source]#

Format the specified records and return the result as a string.

formatFooter(records)[source]#

Return the footer string for the specified records.

formatHeader(records)[source]#

Return the header string for the specified records.

class univention.logging.FileHandler(filename, mode='a', encoding=None, delay=False, errors=None)[source]#

Bases: StreamHandler

A handler class which writes formatted logging records to disk files.

Open the specified file and use it as the stream for logging.

close()[source]#

Closes the stream.

emit(record)[source]#

Emit a record.

If the stream was not opened because ‘delay’ was specified in the constructor, open it before calling the superclass’s emit.

If stream is not open, current mode is ‘w’ and _closed=True, record will not be emitted (see Issue #42378).

class univention.logging.Filter(name='')[source]#

Bases: object

Filter instances are used to perform arbitrary filtering of LogRecords.

Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with “A.B” will allow events logged by loggers “A.B”, “A.B.C”, “A.B.C.D”, “A.B.D” etc. but not “A.BB”, “B.A.B” etc. If initialized with the empty string, all events are passed.

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

filter(record)[source]#

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class univention.logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]#

Bases: object

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

converter()#
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,

tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.

default_msec_format = '%s,%03d'#
default_time_format = '%Y-%m-%d %H:%M:%S'#
format(record)[source]#

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

formatException(ei)[source]#

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

formatMessage(record)[source]#
formatStack(stack_info)[source]#

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

formatTime(record, datefmt=None)[source]#

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

usesTime()[source]#

Check if the format uses the creation time of the record.

class univention.logging.Handler(level=0)[source]#

Bases: Filterer

Handler instances dispatch logging events to specific destinations.

The base handler class. Acts as a placeholder which defines the Handler interface. Handlers can optionally use Formatter instances to format records as desired. By default, no formatter is specified; in this case, the ‘raw’ message as determined by record.message is logged.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

acquire()[source]#

Acquire the I/O thread lock.

close()[source]#

Tidy up any resources used by the handler.

This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.

createLock()[source]#

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)[source]#

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

flush()[source]#

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

format(record)[source]#

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

get_name()[source]#
handle(record)[source]#

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

handleError(record)[source]#

Handle errors which occur during an emit() call.

This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.

property name#
release()[source]#

Release the I/O thread lock.

setFormatter(fmt)[source]#

Set the formatter for this handler.

setLevel(level)[source]#

Set the logging level of this handler. level must be an int or a str.

set_name(name)[source]#
class univention.logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs)[source]#

Bases: object

A LogRecord instance represents an event being logged.

LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args, which are combined using str(msg) % args to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged.

Initialize a logging record with interesting information.

getMessage()[source]#

Return the message for this LogRecord.

Return the message for this LogRecord after merging any user-supplied arguments with the message.

class univention.logging.LoggerAdapter(logger, extra=None)[source]#

Bases: object

An adapter for loggers which makes it easier to specify contextual information in logging output.

Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired.

You can effectively pass keyword arguments as shown in the following example:

adapter = LoggerAdapter(someLogger, dict(p1=v1, p2=”v2”))

critical(msg, *args, **kwargs)[source]#

Delegate a critical call to the underlying logger.

debug(msg, *args, **kwargs)[source]#

Delegate a debug call to the underlying logger.

error(msg, *args, **kwargs)[source]#

Delegate an error call to the underlying logger.

exception(msg, *args, exc_info=True, **kwargs)[source]#

Delegate an exception call to the underlying logger.

getEffectiveLevel()[source]#

Get the effective level for the underlying logger.

hasHandlers()[source]#

See if the underlying logger has any handlers.

info(msg, *args, **kwargs)[source]#

Delegate an info call to the underlying logger.

isEnabledFor(level)[source]#

Is this logger enabled for level ‘level’?

log(level, msg, *args, **kwargs)[source]#

Delegate a log call to the underlying logger, after adding contextual information from this adapter instance.

property manager#
property name#
process(msg, kwargs)[source]#

Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs.

Normally, you’ll only need to override this one method in a LoggerAdapter subclass for your specific needs.

setLevel(level)[source]#

Set the specified level on the underlying logger.

warn(msg, *args, **kwargs)[source]#
warning(msg, *args, **kwargs)[source]#

Delegate a warning call to the underlying logger.

class univention.logging.NullHandler(level=0)[source]#

Bases: Handler

This handler does nothing. It’s intended to be used to avoid the “No handlers could be found for logger XXX” one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

createLock()[source]#

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)[source]#

Stub.

handle(record)[source]#

Stub.

class univention.logging.StreamHandler(stream=None)[source]#

Bases: Handler

A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used.

Initialize the handler.

If stream is not specified, sys.stderr is used.

emit(record)[source]#

Emit a record.

If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.

flush()[source]#

Flushes the stream.

setStream(stream)[source]#

Sets the StreamHandler’s stream to the specified value, if it is different.

Returns the old stream, if the stream was changed, or None if it wasn’t.

terminator = '\n'#
univention.logging.addLevelName(level, levelName)[source]#

Associate ‘levelName’ with ‘level’.

This is used when converting levels to text during message formatting.

univention.logging.captureWarnings(capture)[source]#

If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations.

univention.logging.critical(msg, *args, **kwargs)[source]#

Log a message with severity ‘CRITICAL’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

univention.logging.debug(msg, *args, **kwargs)[source]#

Log a message with severity ‘DEBUG’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

univention.logging.disable(level=50)[source]#

Disable all logging calls of severity ‘level’ and below.

univention.logging.error(msg, *args, **kwargs)[source]#

Log a message with severity ‘ERROR’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

univention.logging.exception(msg, *args, exc_info=True, **kwargs)[source]#

Log a message with severity ‘ERROR’ on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format.

univention.logging.fatal(msg, *args, **kwargs)[source]#

Don’t use this function, use critical() instead.

univention.logging.getLevelName(level)[source]#

Return the textual or numeric representation of logging level ‘level’.

If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with ‘level’ is returned.

If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned.

If a string representation of the level is passed in, the corresponding numeric value is returned.

If no matching numeric or string value is passed in, the string ‘Level %s’ % level is returned.

univention.logging.getLoggerClass()[source]#

Return the class to be used when instantiating a logger.

univention.logging.info(msg, *args, **kwargs)[source]#

Log a message with severity ‘INFO’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

univention.logging.log(level, msg, *args, **kwargs)[source]#

Log ‘msg % args’ with the integer severity ‘level’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

univention.logging.makeLogRecord(dict)[source]#

Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance.

univention.logging.setLoggerClass(klass)[source]#

Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()

univention.logging.shutdown(handlerList=[<weakref at 0x7f8f10bac220; to 'StreamHandler'>, <weakref at 0x7f8f1da946d0; to 'StreamHandler'>, <weakref at 0x7f8f10c75a80; to 'AdminEmailHandler'>, <weakref at 0x7f8f0b8c4220; to 'FileHandler'>, <weakref at 0x7f8f0a2d86d0; to 'FileHandler'>, <weakref at 0x7f8f09c67a60; to 'FileHandler'>, <weakref at 0x7f8f09b5e1b0; to 'FileHandler'>, <weakref at 0x7f8f09b5e2a0; to 'FileHandler'>, <weakref at 0x7f8f09b5e390; to 'FileHandler'>, <weakref at 0x7f8f095c6160; to 'StreamHandler'>, <weakref at 0x7f8f0719df30; to 'UniFileHandler'>])[source]#

Perform any cleanup actions in the logging system (e.g. flushing buffers).

Should be called at application exit.

univention.logging.warn(msg, *args, **kwargs)[source]#
univention.logging.warning(msg, *args, **kwargs)[source]#

Log a message with severity ‘WARNING’ on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.

univention.logging.getLogRecordFactory()[source]#

Return the factory to be used when instantiating a log record.

univention.logging.setLogRecordFactory(factory)[source]#
univention.logging.getLevelNamesMapping()[source]#

univention.password module#

exception univention.password.CheckFailed[source]#

Bases: Exception

class univention.password.Check(lo, username=None)[source]#

Bases: object

check(password, username=None, displayname=None)[source]#
univention.password.password_config(scope=None)[source]#

Read password configuration options from UCR.

Parameters:

scope (str) – UCR scope in which password configuration options are searched for. Default is None.

Returns:

Password configuration options.

Return type:

dict

univention.password.generate_password(digits=6, lower=6, other=0, upper=6, forbidden='', min_length=24)[source]#

Generate random password using given parameters. Whitespaces are implicitly forbidden.

Parameters:
  • digits (int) – Minimal number of digits in generated password. 0 excludes it from the password.

  • lower (int) – Minimal number of lowercase ASCII letters in generated password. 0 excludes it from the password.

  • other (int) – Minimal number of special characters in generated password. 0 excludes it from the password.

  • upper (int) – Minimal number of uppercase ASCII letters in generated password. 0 excludes it from the password.

  • forbidden (str) – Forbidden characters in generated password.

  • min_length (int) – Minimal length of generated password.

Returns:

Randomly generated password.

Return type:

str

Raises:

ValueError – In case any password quality precondition fails.

univention.pkgdb module#

Univention Package Database Python module for the package database

univention.pkgdb.parse_options()[source]#
parse options and return <options> with

<options.debug> <options.action> <options.system> <options.db_server> set

univention.pkgdb.log(message)[source]#

Log-Funktion

univention.pkgdb.build_sysversion(config_registry)[source]#
univention.pkgdb.sql_check_privileges(cursor)[source]#

DB-Privs testen (leerer Zugriff)

univention.pkgdb.get_dbservername(domainname: str) str | None[source]#

Datenbankserver ermitteln

univention.pkgdb.sql_test_superuser(cursor)[source]#

Prüfe auf Superuser

univention.pkgdb.sql_grant_system(connection, cursor, sysname)[source]#

Datenbankbenutzer hinzufügen

univention.pkgdb.sql_revoke_system(connection, cursor, sysname)[source]#

Datenbankbenutzer entfernen

univention.pkgdb.sql_put_sys_in_systems(cursor, sysname, sysversion, sysrole, ldaphostdn, architecture)[source]#

insert a system name into the system-table (or update its data)

univention.pkgdb.sql_put_sys_in_systems_no_architecture(cursor, sysname, sysversion, sysrole, ldaphostdn)[source]#

insert a system name into the old system-table (or update its data)

univention.pkgdb.sql_select(cursor, sqlcmd)[source]#

SQL Selects

univention.pkgdb.sql_getall_systems(cursor)[source]#
univention.pkgdb.sql_getall_systemroles(cursor)[source]#
univention.pkgdb.sql_getall_systemversions(cursor)[source]#
univention.pkgdb.sql_getall_packages_in_systems(cursor)[source]#
univention.pkgdb.sql_get_systems_by_query(cursor, query)[source]#
univention.pkgdb.sql_get_packages_in_systems_by_query(cursor, query, join_systems, limit=None, orderby='sysname, pkgname, vername')[source]#
univention.pkgdb.dump_systems(cursor)[source]#

writes CSV with all systems and their system-specific information to stdout

univention.pkgdb.dump_packages(cursor)[source]#
univention.pkgdb.dump_systems_packages(cursor)[source]#
univention.pkgdb.action_remove_system(connection, cursor, sysname)[source]#

removes system <sysname> from the database

univention.pkgdb.scan_and_store_packages(cursor, sysname, fake_null=False, architecture=None)[source]#

updates the system <sysname> with the current package state if <fake_null> is True put ‘’ instead of None in the vername field

univention.pkgdb.action_fill_testdb(connection, cursor, config_registry)[source]#

Fülle Testdatenbank

univention.pkgdb.action_scan(connection, cursor, config_registry)[source]#

put systems <sysname> in the database and updates it with the current package state

univention.pkgdb.open_database_connection(config_registry, pkgdbu=False, db_server=None)[source]#
univention.pkgdb.main()[source]#

main function for univention-pkgdb-scan

univention.service_info module#

exception univention.service_info.ServiceError[source]#

Bases: Exception

Error when starting, stopping or restarting a service.

class univention.service_info.Service(*args: Any, **kwargs: Any)[source]#

Bases: LocalizedDictionary

Description for a system service.

REQUIRED = frozenset({'description', 'programs'})#
OPTIONAL = frozenset({'icon', 'init_script', 'name', 'start_type', 'systemd'})#
KNOWN = frozenset({'description', 'icon', 'init_script', 'name', 'programs', 'start_type', 'systemd'})#
check() list[str][source]#

Check service entry for validity, returning list of incomplete entries.

start() bool[source]#

Start the service.

stop() bool[source]#

Stop the service.

restart() bool[source]#

Restart the service.

status()[source]#

Get status of the service.

univention.service_info.pidof(name: str, docker: int | str = '/var/run/docker.pid') list[int][source]#

Return list of process IDs matching name.

Parameters:
  • name – Procress name.

  • docker – File name containing process ID of docker process.

>>> import os,sys;os.getpid() in list(pidof(os.path.realpath(sys.executable))) + list(pidof(sys.executable)) + list(pidof(sys.argv[0]))
True
class univention.service_info.ServiceInfo(install_mode: bool = False)[source]#

Bases: object

BASE_DIR = '/etc/univention/service.info'#
SERVICES = 'services'#
CUSTOMIZED = '_customized'#
FILE_SUFFIX = '.cfg'#
update_services() None[source]#

Update the run state of all services.

check_services() dict[str, list[str]][source]#

Check service descriptions for completeness.

Returns:

dictionary of incomplete service descriptions.

write_customized() bool[source]#

Save service cusomization.

read_services(filename: str | None = None, package: str | None = None, override: bool = False) None[source]#

Read start/stop levels of services.

Parameters:
  • filename – Explicit filename for loading.

  • package – Explicit package name.

  • overrideTrue to overwrite already loaded descriptions.

Raises:

AttributeError – if neither filename nor package are given.

read_customized() None[source]#

Read service cusomization.

get_services() Iterable[str][source]#

Return a list fo service names.

Returns:

List of service names.

get_service(name: str) Service | None[source]#

Return the service object associated with the given name.

Parameters:

name – Service name.

Returns:

description object or None.

add_service(name: str, service: Service) None[source]#

Add a new service object or overrides an old entry.

Parameters:
  • name – Service name.

  • serviceService instance.

univention.uldap module#

univention.uldap.parentDn(dn: str, base: str = '') str | None[source]#

Return the parent container of a distinguished name.

Parameters:
  • dn (str) – The distinguished name.

  • base (str) – distinguished name where to stop.

Returns:

The parent distinguished name or None.

Return type:

str or None

univention.uldap.explodeDn(dn: str, notypes: int = 0) list[str][source]#

Break up a DN into its component parts.

Parameters:
  • dn (str) – The distinguished name.

  • notypes (int) – Return only the component’s attribute values if True. Also the attribute types if False.

Returns:

A list of relative distinguished names.

Return type:

list[str]

univention.uldap.getRootDnConnection(start_tls: int | None = None, decode_ignorelist: None = None, reconnect: bool = True) access[source]#

Open a LDAP connection to the local LDAP server with the LDAP root account.

Parameters:
  • start_tls (int) – Negotiate TLS with server. If 2 is given, the command will require the operation to be successful.

  • reconnect (bool) – Automatically reconect if the connection fails.

Returns:

A LDAP access object.

Return type:

univention.uldap.access

univention.uldap.getAdminConnection(start_tls: int | None = None, decode_ignorelist: None = None, reconnect: bool = True) access[source]#

Open a LDAP connection to the Primary Directory Node LDAP server using the admin credentials.

Parameters:
  • start_tls (int) – Negotiate TLS with server. If 2 is given, the command will require the operation to be successful.

  • reconnect (bool) – Automatically reconect if the connection fails.

Returns:

A LDAP access object.

Return type:

univention.uldap.access

univention.uldap.getBackupConnection(start_tls: int | None = None, decode_ignorelist: None = None, reconnect: bool = True) access[source]#

Open a LDAP connection to a Backup Directory Node LDAP server using the admin credentials.

Parameters:
  • start_tls (int) – Negotiate TLS with server. If 2 is given, the command will require the operation to be successful.

  • reconnect (bool) – Automatically reconect if the connection fails.

Returns:

A LDAP access object.

Return type:

univention.uldap.access

univention.uldap.getMachineConnection(start_tls: int | None = None, decode_ignorelist: None = None, ldap_master: bool = True, secret_file: str = '/etc/machine.secret', reconnect: bool = True, random_server: bool = False) access[source]#

Open a LDAP connection using the machine credentials.

Parameters:
  • start_tls (int) – Negotiate TLS with server. If 2 is given, the command will require the operation to be successful.

  • ldap_master (bool) – Open a connection to the Master if True, to the preferred LDAP server otherwise.

  • secret_file (str) – The name of a file containing the password credentials.

  • reconnect (bool) – Automatically reconnect if the connection fails.

  • random_server (bool) – Choose a random LDAP server from ldap/server/name and ldap/server/addition.

Returns:

A LDAP access object.

Return type:

univention.uldap.access

class univention.uldap.access(host: str = 'localhost', port: int | None = None, base: str = '', binddn: str | None = '', bindpw: str = '', start_tls: int | None = None, ca_certfile: str | None = None, decode_ignorelist: None = None, use_ldaps: bool = False, uri: str | None = None, follow_referral: bool = False, reconnect: bool = True)[source]#

Bases: object

The low-level class to access a LDAP server.

Parameters:
  • host (str) – host name of the LDAP server.

  • port (int) – TCP port of the LDAP server. Defaults to 7389 or 7636.

  • base (str) – LDAP base distinguished name.

  • binddn (str) – Distinguished name for simple authentication.

  • bindpw (str) – Password for simple authentication.

  • start_tls (int) – 0=no, 1=try StartTLS, 2=require StartTLS.

  • ca_certfile (str) – File name to CA certificate.

  • decode_ignorelist – obsolete

  • use_ldaps (bool) – Connect to SSL port.

  • uri (str) – LDAP connection string.

  • follow_referral (bool) – Follow referrals and return result from other servers instead of returning the referral itself.

  • reconnect (bool) – Automatically re-establish connection to LDAP server if connection breaks.

property authz_connection#
bind(binddn: str, bindpw: str) None[source]#

Do simple LDAP bind using DN and password.

Parameters:
  • binddn (str) – The distinguished name of the account.

  • bindpw (str) – The user password for simple authentication.

bind_saml(bindpw: str) None[source]#

Do LDAP bind using SAML message.

Parameters:

bindpw (str) – The SAML authentication cookie.

bind_oauthbearer(authzid: str | None, bindpw: str) None[source]#

Do LDAP bind using OAuth 2.0 Access Token.

Parameters:
  • authzid (str) – Authorization Identifier

  • bindpw (str) – The Access Token (as JWT)

OAUTHBEARER follows RFC 7628. Currently sending an optional authzid which could be used for SASL Proxy Authorization in the future (https://www.openldap.org/doc/admin26/sasl.html#SASL%20Proxy%20Authorization).

unbind() None[source]#

Unauthenticate.

whoami() str[source]#

Return the distinguished name of the authenticated user.

Returns:

The distinguished name.

Return type:

str

get(dn: str, attr: list[str] = [], required: bool = False) dict[str, list[bytes]][source]#

Return multiple attributes of a single LDAP object.

Parameters:
  • dn (str) – The distinguished name of the object to lookup.

  • attr (list[str]) – The list of attributes to fetch.

  • required (bool) – Raise an exception instead of returning an empty dictionary.

Returns:

A dictionary mapping the requested attributes to a list of their values.

Return type:

dict[str, list[bytes]]

Raises:

ldap.NO_SUCH_OBJECT – If the LDAP object is not accessible.

getAttr(dn: str, attr: str, required: bool = False) list[bytes][source]#

Return a single attribute of a single LDAP object.

Parameters:
  • dn (str) – The distinguished name of the object to lookup.

  • attr (str) – The attribute to fetch.

  • required (bool) – Raise an exception instead of returning an empty dictionary.

Returns:

A list of values.

Return type:

list[bytes]

Raises:

ldap.NO_SUCH_OBJECT – If the LDAP object is not accessible.

Warning

the attribute name is currently case sensitive and must be given as in the LDAP schema

Warning

when required=True it raises ldap.NO_SUCH_OBJECT even if the object exists but the attribute is not set

search(filter: str = '(objectClass=*)', base: str = '', scope: str = 'sub', attr: list[str] = [], unique: bool = False, required: bool = False, timeout: int = -1, sizelimit: int = 0, serverctrls: list[LDAPControl] | None = None, response: dict[str, LDAPControl] | None = None) list[tuple[str, dict[str, list[bytes]]]][source]#

Perform LDAP search and return values.

Parameters:
  • filter (str) – LDAP search filter.

  • base (str) – the starting point for the search.

  • scope (str) – Specify the scope of the search to be one of base, base+one, one, sub, or domain to specify a base object, base plus one-level, one-level, subtree, or children search.

  • attr (list[str]) – The list of attributes to fetch.

  • unique (bool) – Raise an exception if more than one object matches.

  • required (bool) – Raise an exception instead of returning an empty dictionary.

  • timeout (int) – wait at most timeout seconds for a search to complete. -1 for no limit.

  • sizelimit (int) – retrieve at most sizelimit entries for a search. 0 for no limit.

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request.

  • response (dict) – An optional dictionary to receive the server controls of the result.

Returns:

A list of 2-tuples (dn, values) for each LDAP object, where values is a dictionary mapping attribute names to a list of values.

Return type:

list[tuple[str, dict[str, list[bytes]]]]

Raises:
  • ldap.NO_SUCH_OBJECT – Indicates the target object cannot be found.

  • ldap.INAPPROPRIATE_MATCHING – Indicates that the matching rule specified in the search filter does not match a rule defined for the attribute’s syntax.

searchDn(filter: str = '(objectClass=*)', base: str = '', scope: str = 'sub', unique: bool = False, required: bool = False, timeout: int = -1, sizelimit: int = 0, serverctrls: list[LDAPControl] | None = None, response: dict[str, LDAPControl] | None = None) list[str][source]#

Perform LDAP search and return distinguished names only.

Parameters:
  • filter (str) – LDAP search filter.

  • base (str) – the starting point for the search.

  • scope (str) – Specify the scope of the search to be one of base, base+one, one, sub, or domain to specify a base object, base plus one-level, one-level, subtree, or children search.

  • unique (bool) – Raise an exception if more than one object matches.

  • required (bool) – Raise an exception instead of returning an empty dictionary.

  • timeout (int) – wait at most timeout seconds for a search to complete. -1 for no limit.

  • sizelimit (int) – retrieve at most sizelimit entries for a search. 0 for no limit.

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request.

  • response (dict) – An optional dictionary to receive the server controls of the result.

Returns:

A list of distinguished names.

Return type:

list[str]

Raises:
  • ldap.NO_SUCH_OBJECT – Indicates the target object cannot be found.

  • ldap.INAPPROPRIATE_MATCHING – Indicates that the matching rule specified in the search filter does not match a rule defined for the attribute’s syntax.

getPolicies(dn: str, policies: list[str] | None = None, attrs: dict[str, list[Any]] | None = None, result: Any = None, fixedattrs: Any = None) dict[str, dict[str, Any]][source]#

Return UCS policies for LDAP entry.

Parameters:
  • dn (str) – The distinguished name of the LDAP entry.

  • policies (list) – List of policy object classes…

  • attrs (dict) – LDAP attributes. If not given, the data is fetched from LDAP.

  • result – UNUSED!

  • fixedattrs – UNUSED!

Returns:

A mapping of policy names to

get_schema() SubSchema[source]#

Retrieve LDAP schema information from LDAP server.

Returns:

The LDAP schema.

Return type:

ldap.schema.subentry.SubSchema

add(dn: str, al: list[tuple], serverctrls: list[LDAPControl] | None = None, response: dict | None = None) None[source]#

Add LDAP entry at distinguished name and attributes in add_list=(attribute-name, old-values. new-values) or (attribute-name, new-values).

Parameters:
  • dn (str) – The distinguished name of the object to add.

  • al – The add-list of 2-tuples (attribute-name, new-values).

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request

  • response (dict) – An optional dictionary to receive the server controls of the result.

modify(dn: str, changes: list[tuple[str, Any, Any]], serverctrls: list[LDAPControl] | None = None, response: dict | None = None, rename_callback: Callable | None = None) str[source]#

Modify LDAP entry DN with attributes in changes=(attribute-name, old-values, new-values).

Parameters:
  • dn (str) – The distinguished name of the object to modify.

  • changes – The modify-list of 3-tuples (attribute-name, old-values, new-values).

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request

  • response (dict) – An optional dictionary to receive the server controls of the result.

Returns:

The distinguished name.

Return type:

str

modify_s(dn: str, ml: list[tuple[str, list[str] | None, list[str]]]) None[source]#

Redirect modify_s directly to lo.

Parameters:
  • dn (str) – The distinguished name of the object to modify.

  • ml – The modify-list of 3-tuples (attribute-name, old-values, new-values).

modify_ext_s(dn: str, ml: list[tuple[str, Any, Any]], serverctrls: list[LDAPControl] | None = None, response: dict | None = None) None[source]#

Redirect modify_ext_s directly to lo.

Parameters:
  • dn (str) – The distinguished name of the object to modify.

  • ml – The modify-list of 3-tuples (attribute-name, old-values, new-values).

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request

  • response (dict) – An optional dictionary to receive the server controls of the result.

rename(dn: str, newdn: str, serverctrls: list[LDAPControl] | None = None, response: dict | None = None) None[source]#

Rename a LDAP object.

Parameters:
  • dn (str) – The old distinguished name of the object to rename.

  • newdn (str) – The new distinguished name of the object to rename.

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request

  • response (dict) – An optional dictionary to receive the server controls of the result.

rename_ext_s(dn: str, newrdn: str, newsuperior: str | None = None, serverctrls: list[LDAPControl] | None = None, response: dict | None = None) None[source]#

Redirect rename_ext_s directly to lo.

Parameters:
  • dn (str) – The old distinguished name of the object to rename.

  • newdn (str) – The new distinguished name of the object to rename.

  • newsuperior (str) – The distinguished name of the new container.

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request

  • response (dict) – An optional dictionary to receive the server controls of the result.

delete(dn, serverctrls=None, response=None) None[source]#

Delete a LDAP object.

Parameters:
  • dn (str) – The distinguished name of the object to remove.

  • serverctrls (list[ldap.controls.LDAPControl]) – a list of ldap.controls.LDAPControl instances sent to the server along with the LDAP request.

  • response (dict) – An optional dictionary to receive the server controls of the result.

parentDn(dn: str) str | None[source]#

Return the parent container of a distinguished name.

Parameters:

dn (str) – The distinguished name.

Returns:

The parent distinguished name or None if the LDAP base is reached.

Return type:

str or None

explodeDn(dn: str, notypes: bool | int = False) list[str][source]#

Break up a DN into its component parts.

Parameters:
  • dn (str) – The distinguished name.

  • notypes (bool) – Return only the component’s attribute values if True. Also the attribute types if False.

Returns:

A list of relative distinguished names.

Return type:

list[str]

classmethod compare_dn(a: str, b: str) bool[source]#

Test DNs are same

Parameters:
  • a (str) – The first distinguished name.

  • b (str) – A second distinguished name.

Returns:

True if the DNs are the same, False otherwise.

Return type:

bool

>>> compare_dn = access.compare_dn
>>> compare_dn('foo=1', 'foo=1')
True
>>> compare_dn('foo=1', 'foo=2')
False
>>> compare_dn('Foo=1', 'foo=1')
True
>>> compare_dn('Foo=1', 'foo=2')
False
>>> compare_dn('foo=1,bar=2', 'foo=1,bar=2')
True
>>> compare_dn('bar=2,foo=1', 'foo=1,bar=2')
False
>>> compare_dn('foo=1+bar=2', 'foo=1+bar=2')
True
>>> compare_dn('bar=2+foo=1', 'foo=1+bar=2')
True
>>> compare_dn('bar=2+Foo=1', 'foo=1+Bar=2')
True
>>> compare_dn(r'foo=\31', r'foo=1')
True