univention package

Subpackages

Submodules

univention.baseconfig module

univention.config_registry_info module

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

Bases: univention.info_tools.LocalizedDictionary

UCR variable description.

check()[source]

Check description for completeness.

Returns:List of missing settings.
class univention.config_registry_info.Category[source]

Bases: univention.info_tools.LocalizedDictionary

UCR category description.

check()[source]

Check description for completeness.

Returns:List of missing settings.
class univention.config_registry_info.ConfigRegistryInfo(install_mode=False, registered_only=True, load_customized=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()[source]

Check all categories for completeness.

Returns:dictionary of incomplete category descriptions.
check_variables()[source]

Check variables.

Returns:dictionary of incomplete variable descriptions.
read_categories(filename)[source]

Load a single category description file.

Parameters:filename – File to load.
load_categories()[source]

Load all category description files.

check_patterns()[source]

Match descriptions agains currently defined UCR variables.

describe_search_term(term)[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()[source]

Persist the customized variable descriptions.

read_customized()[source]

Read customized variable descriptions.

read_variables(filename=None, package=None, override=False)[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()[source]

Return a list of category names.

Returns:List if categories.
get_category(name)[source]

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

Parameters:name – Name of the category.
Returns:
get_variables(category=None)[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)[source]

Return the description of a variable.

Parameters:key – Variable name.
Returns:description object or None.
add_variable(key, variable)[source]

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

Parameters:
  • key – Variable name.
  • variableVariable instance.
_ConfigRegistryInfo__load_variables(registered_only=True, load_customized=True)

Read default and customized variable descriptions.

Parameters:
  • registered_only – With default True only variables for which a description exists are loaded, otherwise all currently set variables are also included.
  • load_customized – Load customized variable descriptions.
static _ConfigRegistryInfo__pattern_sorter(args)

Sort more specific (longer) regular expressions first.

_ConfigRegistryInfo__write_variables(filename=None, package=None)

Persist the variable descriptions into a file.

Parameters:
  • filename – Explicit filename for saving.
  • package – Explicit package name.
Raises:

AttributeError – if neither filename nor package are given.

Returns:

True on success, False otherwise.

univention.config_registry_info.set_language(lang)[source]

Set the default language.

univention.debhelper module

Debhelper compatible routines.

univention.debhelper.doIt(*argv)[source]

Execute argv and wait.

Parameters:args – List of command and arguments.
>>> doIt('true')
0
univention.debhelper.binary_packages()[source]

Get list of binary packages from debian/control file.

>>> binary_packages() 
[...]
univention.debhelper.parseRfc822(f)[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.debug module

Univention debugging and logging library.

example:

>>> f = init('stdout', NO_FLUSH, FUNCTION) 
... ...  DEBUG_INIT
>>> set_level(LISTENER, ERROR)
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
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.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
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
  • 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.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._flush()[source]

Flushing all messages.

univention.dns module

univention.dns.lookup(query, type='a')[source]

Lookup DNS entries of specified type.

>>> lookup('localhost')
['127.0.0.1']

univention.fstab module

Handle parsing and writing /etc/fstab.

See <http://linux.die.net/include/mntent.h>.

class univention.fstab.mntent(fsname, dir, type, opts=None, freq=0, passno=0, comment=None)[source]

Bases: object

Structure describing a mount table entry.

classmethod quote(s)[source]

Quote string to octal. >>> mntent.quote(‘a b’) ‘a\040b’

classmethod unquote(s)[source]

Unquote octal to string. >>> mntent.unquote(‘a040b’) ‘a b’

hasopt(opt)[source]

Search for an option matching OPT. >>> mntent(‘/dev/sda’, ‘/’, ‘ext3’, ‘default,ro,user_xattr,acl’, 0, 0).hasopt(‘user’) [‘user_xattr’]

class univention.fstab.fstab(fstab='/etc/fstab')[source]

Bases: object

Handle parsing and writing /etc/fstab.

remove(entry)[source]

Remove entry.

append(entry)[source]

Add entry.

_fstab__load()

Load and parse fstab.

save(fn=None)[source]

Save new fstab.

univention.hooks module

class univention.hooks.HookManager(module_dir, raise_exceptions=True)[source]

This class tries to provide a simple interface to load and call hooks within existing code. Python modules are loaded from specified module_dir and automatically registered. These python modules have to contain at least a global method register_hooks() that returns a list of tuples (hook_name, callable).

Simple hook file example:

def my_test_hook(*args, **kwargs):
        print('TEST_HOOK:', args, kwargs)
        return ['Mein', 'Result', 123]

def other_hook(*args, **kwargs):
        print('MY_SECOND_TEST_HOOK:', args, kwargs)
        return ['Mein', 'Result', 123]

def register_hooks():
        return [
                ('test_hook', my_test_hook),
                ('pre_hook', other_hook),
        ]

The method call_hook(hookname, *args, **kwargs) calls all registered methods for specified hookname and passes *args and **kwargs to them. The return value of each method will be saved and returned by call_hook() as a list. If no method has been registered for specified hookname, an empty list will be returned.

If raise_exceptions has been set to False, exceptions while loading Python modules will be discarded silently. If a hook raises an exception, it will be caught and returned in result list of call_hooks() instead of corresponding return value. E.g.:

[['Mein', 'Result', 123], <exceptions.ValueError instance at 0x7f80496f6638>]

How to use HookManager:

>>> import univention.hooks
>>> hm = univention.hooks.HookManager('./test')
>>> hm.get_hook_list()

[‘test_hook’, ‘pre_hook’] >>> hm.call_hook(‘test_hook’, ‘abc’, 123, x=1, y=’B’) TEST_HOOK: (‘abc’, 123) {‘y’: ‘B’, ‘x’: 1} <=== OUTPUT OF FIRST TESTHOOK MY_SECOND_TEST_HOOK: (‘abc’, 123) {‘y’: ‘B’, ‘x’: 1} <=== OUTPUT OF SECOND TESTHOOK [[‘First-Hook’, ‘Result’, 123], [‘Result’, ‘of’, ‘second’, ‘testhook’]] <=== RESULT OF call_hook() >>> hm.call_hook(‘unknown_hook’) [] >>>

Parameters:
  • module_dir – path to directory that contains python modules with hook functions
  • raise_exceptions – if False, all exceptions while loading python modules will be dropped and all exceptions while calling hooks will be caught and returned in result list
set_raise_exceptions(val)[source]

Enable or disable raising exceptions.

Parameters:valTrue to pass exceptions through, False to return them instead of the return value.
get_hook_list()[source]

returns a list of hook names that have been defined by loaded python modules

call_hook(name, *args, **kwargs)[source]

All additional arguments are passed to hook methods. If self.__raise_exceptions is False, all exceptions while calling hooks will be caught and returned in result list. If return value is an empty list, no hook has been called.

_HookManager__load_hooks()

loads all python modules in specified module dir

_HookManager__register_hooks()

univention.info_tools module

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

Bases: dict

Localized description entry.

get(locale=None)[source]
set(value, locale=None)[source]
set_default(default)[source]
get_default()[source]
class univention.info_tools.LocalizedDictionary[source]

Bases: dict

Localized descriptions.

_LOCALE_REGEX = <_sre.SRE_Pattern object>
get(key, default=None)[source]
has_key(key)
normalize(key=None)[source]
get_dict(key)[source]
_LocalizedDictionary__normalize_key(key)
class univention.info_tools.UnicodeConfig[source]

Bases: ConfigParser.ConfigParser

write(fp)[source]

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

univention.info_tools.set_language(lang)[source]

univention.ipcalc module

Univention IP Calculator for DNS records (IPv6 edition).

univention.ipcalc.calculate_ipv6_reverse(network)[source]

Return reversed network part of IPv4 network. >>> calculate_ipv6_reverse(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/0’)) ‘0’ >>> calculate_ipv6_reverse(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/1’)) ‘0’ >>> calculate_ipv6_reverse(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/4’)) ‘0’ >>> calculate_ipv6_reverse(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/16’)) ‘0123’ >>> calculate_ipv6_reverse(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/124’)) ‘0123:4567:89ab:cdef:0123:4567:89ab:cde’ >>> calculate_ipv6_reverse(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/128’)) ‘0123:4567:89ab:cdef:0123:4567:89ab:cde’

univention.ipcalc.calculate_ipv4_reverse(network)[source]

Return reversed network part of IPv4 network. >>> calculate_ipv4_reverse(ipaddr.IPv4Network(‘1.2.3.4/0’)) ‘1’ >>> calculate_ipv4_reverse(ipaddr.IPv4Network(‘1.2.3.4/8’)) ‘1’ >>> calculate_ipv4_reverse(ipaddr.IPv4Network(‘1.2.3.4/16’)) ‘1.2’ >>> calculate_ipv4_reverse(ipaddr.IPv4Network(‘1.2.3.4/24’)) ‘1.2.3’ >>> calculate_ipv4_reverse(ipaddr.IPv4Network(‘1.2.3.4/32’)) ‘1.2.3’

univention.ipcalc.calculate_ipv6_network(network)[source]

Return network part of IPv6 network. >>> calculate_ipv6_network(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/0’)) ‘’ >>> calculate_ipv6_network(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/1’)) ‘’ >>> calculate_ipv6_network(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/4’)) ‘0’ >>> calculate_ipv6_network(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/16’)) ‘0123’ >>> calculate_ipv6_network(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/112’)) ‘0123:4567:89ab:cdef:0123:4567:89ab’ >>> calculate_ipv6_network(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/128’)) ‘0123:4567:89ab:cdef:0123:4567:89ab:cdef’

univention.ipcalc.calculate_ipv4_network(network)[source]

Return network part of IPv4 network. >>> calculate_ipv4_network(ipaddr.IPv4Network(‘1.2.3.4/0’)) ‘’ >>> calculate_ipv4_network(ipaddr.IPv4Network(‘1.2.3.4/1’)) ‘’ >>> calculate_ipv4_network(ipaddr.IPv4Network(‘1.2.3.4/8’)) ‘1’ >>> calculate_ipv4_network(ipaddr.IPv4Network(‘1.2.3.4/24’)) ‘1.2.3’ >>> calculate_ipv4_network(ipaddr.IPv4Network(‘1.2.3.4/32’)) ‘1.2.3.4’

univention.ipcalc.calculate_ipv6_pointer(network)[source]

Return host part of IPv6 network. >>> calculate_ipv6_pointer(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/0’)) ‘f.e.d.c.b.a.9.8.7.6.5.4.3.2.1.0.f.e.d.c.b.a.9.8.7.6.5.4.3.2.1’ >>> calculate_ipv6_pointer(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/1’)) ‘f.e.d.c.b.a.9.8.7.6.5.4.3.2.1.0.f.e.d.c.b.a.9.8.7.6.5.4.3.2.1’ >>> calculate_ipv6_pointer(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/4’)) ‘f.e.d.c.b.a.9.8.7.6.5.4.3.2.1.0.f.e.d.c.b.a.9.8.7.6.5.4.3.2.1’ >>> calculate_ipv6_pointer(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/124’)) ‘f’ >>> calculate_ipv6_pointer(ipaddr.IPv6Network(‘0123:4567:89ab:cdef:0123:4567:89ab:cdef/128’)) ‘f’

univention.ipcalc.calculate_ipv4_pointer(network)[source]

Return host part of IPv4 network. >>> calculate_ipv4_pointer(ipaddr.IPv4Network(‘1.2.3.4/0’)) ‘4.3.2’ >>> calculate_ipv4_pointer(ipaddr.IPv4Network(‘1.2.3.4/1’)) ‘4.3.2’ >>> calculate_ipv4_pointer(ipaddr.IPv4Network(‘1.2.3.4/8’)) ‘4.3.2’ >>> calculate_ipv4_pointer(ipaddr.IPv4Network(‘1.2.3.4/24’)) ‘4’ >>> calculate_ipv4_pointer(ipaddr.IPv4Network(‘1.2.3.4/32’)) ‘4’

univention.ipcalc.main()[source]

Run internal test suite.

univention.ipv4 module

univention.ipv4.splitDotted(ip)[source]

Split IPv4 address from dotted quad string.

>>> splitDotted('1.2.3.4')
[1, 2, 3, 4]
univention.ipv4.joinDotted(ip)[source]

Convert IPv4 address to dotted quad string.

>>> joinDotted([1, 2, 3, 4])
'1.2.3.4'
univention.ipv4.networkNumber(dottedIp, dottedNetmask)[source]

Calculate network number from dotted quad IPv4 address string and network mask.

>>> networkNumber('1.2.3.4', '255.255.254.0')
'1.2.2.0'
univention.ipv4.broadcastNumber(dottedNetwork, dottedNetmask)[source]

Calculate broadcast address from dotted quad IPv4 address string and network mask.

>>> broadcastNumber('1.2.2.0', '255.255.254.0')
'1.2.3.255'
>>> broadcastNumber('1.2.3.4', '255.255.254.0')
'1.2.3.255'

univention.misc module

univention.misc.filemax_global()[source]

Get maximum number of files the kernel can open.

>>> filemax_global() 
...
univention.misc.filemax()[source]

Get maximum number of files a process can open.

>>> filemax() 
...
univention.misc.close_fds()[source]

Close all open file descriptors and open /dev/null as stdin, stdout, and stderr.

>>> close_fds()
univention.misc.close_fd_spawn(file, args)[source]

Close all open file descriptors before doing execv().

>>> close_fd_spawn("/bin/bash", ["bash", "-c", "exit `find /proc/$$/fd -mindepth 1 -lname /dev/null | wc -l`"])
3

univention.password module

class univention.password.Check(lo, username=None)[source]
_getConnection()[source]
_systemPolicy()[source]
_userPolicy(username)[source]
check(password)[source]

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)[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: exceptions.Exception

Error when starting, stopping or restarting a service.

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

Bases: univention.info_tools.LocalizedDictionary

Description for a system service.

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

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

_update_status()[source]
start()[source]

Start the service.

stop()[source]

Stop the service.

restart()[source]

Restart the service.

status()[source]

Get status of the service.

_change_state(action)[source]
_service_name()[source]
_exec(args)[source]
_Service__change_state(action)
univention.service_info.pidof(name, docker='/var/run/docker.pid')[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=False)[source]

Bases: object

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

Update the run state of all services.

check_services()[source]

Check service descriptions for completeness.

Returns:dictionary of incomplete service descriptions.
write_customized()[source]

Save service cusomization.

read_services(filename=None, package=None, override=False)[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()[source]

Read service cusomization.

get_services()[source]

Return a list fo service names.

Returns:List of service names.
get_service(name)[source]

Return the service object associated with the given name.

Parameters:name – Service name.
Returns:description object or None.
add_service(name, service)[source]

Add a new service object or overrides an old entry.

Parameters:
  • name – Service name.
  • serviceService instance.
_ServiceInfo__load_services()

Load definition of all defined services.

univention.uldap module

univention.uldap.parentDn(dn, base='')[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, notypes=0)[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=2, decode_ignorelist=[], reconnect=True)[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.
  • decode_ignorelist (list[str]) – List of LDAP attribute names which shall be handled as binary attributes.
  • reconnect (bool) – Automatically reconect if the connection fails.
Returns:

A LDAP access object.

Return type:

univention.uldap.access

univention.uldap.getAdminConnection(start_tls=2, decode_ignorelist=[], reconnect=True)[source]

Open a LDAP connection to the Master 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.
  • decode_ignorelist (list[str]) – List of LDAP attribute names which shall be handled as binary attributes.
  • reconnect (bool) – Automatically reconect if the connection fails.
Returns:

A LDAP access object.

Return type:

univention.uldap.access

univention.uldap.getBackupConnection(start_tls=2, decode_ignorelist=[], reconnect=True)[source]

Open a LDAP connection to a Backup 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.
  • decode_ignorelist (list[str]) – List of LDAP attribute names which shall be handled as binary attributes.
  • reconnect (bool) – Automatically reconect if the connection fails.
Returns:

A LDAP access object.

Return type:

univention.uldap.access

univention.uldap.getMachineConnection(start_tls=2, decode_ignorelist=[], ldap_master=True, secret_file='/etc/machine.secret', reconnect=True, random_server=False)[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.
  • decode_ignorelist (list[str]) – List of LDAP attribute names which shall be handled as binary attributes.
  • 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

univention.uldap._fix_reconnect_handling(func)[source]
class univention.uldap.access(host='localhost', port=None, base='', binddn='', bindpw='', start_tls=2, ca_certfile=None, decode_ignorelist=[], use_ldaps=False, uri=None, follow_referral=False, reconnect=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 – List of LDAP attribute names which shall be handled as binary attributes.
  • bool (reconnect) – Connect to SSL port.
  • str (uri) – LDAP connection string.
  • bool – Follow referrals and return result from other servers instead of returning the referral itself.
  • bool – Automatically re-establish connection to LDAP server if connection breaks.
bind(*args, **kwargs)[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(*args, **kwargs)[source]

Do LDAP bind using SAML message.

Parameters:bindpw (str) – The SAML authentication cookie.
unbind()[source]

Unauthenticate.

whoami()[source]

Return the distinguished name of the authenticated user.

Returns:The distinguished name.
Return type:str
_reconnect()[source]

Reconnect.

get(*args, **kwargs)[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[str]]

Raises:

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

getAttr(*args, **kwargs)[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[str]

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(*args, **kwargs)[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[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.
searchDn(filter='(objectClass=*)', base='', scope='sub', unique=False, required=False, timeout=-1, sizelimit=0, serverctrls=None, response=None)[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(*args, **kwargs)[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

_merge_policy(policy_dn, obj_dn, object_classes, result)[source]

Merge policies into result.

Parameters:
  • str (policy_dn) – Distinguished name of the policy object.
  • obj_dn – Distinguished name of the LDAP object.
  • set (object_classes) – the set of object classes of the LDAP object.
  • list (result) – A mapping, into which the policy is merged.
get_schema(*args, **kwargs)[source]

Retrieve LDAP schema information from LDAP server.

Returns:The LDAP schema.
Return type:ldap.schema.subentry.SubSchema
add(*args, **kwargs)[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(*args, **kwargs)[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(*args, **kwargs)[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(*args, **kwargs)[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, newdn, serverctrls=None, response=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(*args, **kwargs)[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(*args, **kwargs)[source]

Delete a LDAP object.

Parameters:dn (str) – The distinguished name of the object to remove.
_access__decode_attribute(attr, val)
_access__decode_entry(entry)
_access__encode(value)
_access__encode_attribute(attr, val)
_access__encode_entry(entry)
_access__encode_pwd(pwd)
classmethod _access__get_new_dn(dn, ml)
>>> get_dn = access._access__get_new_dn
>>> get_dn('univentionAppID=foo,dc=bar', [(ldap.MOD_REPLACE, 'univentionAppID', 'foo')])[0]
'univentionAppID=foo,dc=bar'
>>> get_dn('univentionAppID=foo,dc=bar', [(ldap.MOD_REPLACE, 'univentionAppID', 'föo')])[0]
'univentionAppID=f\xc3\xb6o,dc=bar'
>>> get_dn('univentionAppID=foo,dc=bar', [(ldap.MOD_REPLACE, 'univentionAppID', 'bar')])[0]
'univentionAppID=bar,dc=bar'
_access__open(ca_certfile)
_access__recode_attribute(attr, val)
_access__recode_entry(entry)
_access__starttls(*args, **kwargs)
parentDn(dn)[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, notypes=False)[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, b)[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
_handle_referral(exception)[source]

Follow LDAP rederral.

Parameters:ldap.REFERRAL (exception) – The LDAP referral exception.
Returns:LDAP connection object for the referred LDAP server.
Return type:ldap.ldapobject.ReconnectLDAPObject

univention.utf8 module

univention.utf8.decode(ob, ignore=[])[source]

Decode object from UTF-8.

>>> decode(None)
>>> decode(chr(0xc3) + chr(0xa4)) == u'ä'
True
>>> decode([chr(0xc3) + chr(0xa4)]) == [u'ä']
True
>>> decode((chr(0xc3) + chr(0xa4),)) == (u'ä',)
True
>>> decode({42: chr(0xc3) + chr(0xa4)}) == {42: u'ä'}
True
>>> decode(set((chr(0xc3) + chr(0xa4),))) == set([u'ä'])
True
univention.utf8.encode(ob)[source]

Encode object to UTF-8.

>>> encode(None)
>>> encode(u'ä')
'\xc3\xa4'
>>> encode([u'ä'])
['\xc3\xa4']
>>> encode((u'ä',))
('\xc3\xa4',)
>>> encode({42: u'ä'})
{42: '\xc3\xa4'}
>>> encode(set((u'ä',)))
set(['\xc3\xa4'])