univention.lib package

Submodules

univention.lib.account module

univention.lib.account.initialize_debug()[source]
univention.lib.account.lock(userdn, lock_timestamp)[source]

Lock a user account

  • used by ppolicy OpenLDAP overlay
  • used by PAM tally
>>> import univention.lib.account
>>> univention.lib.account.lock('uid=user1,dc=example,dc=com', '20141006192950Z')
>>>

univention.lib.admember module

univention.lib.atjobs module

Univention common Python library for handling at jobs.

This module abstracts the handling of at-jobs, each job is encapsulated by the class AtJob. Use the method add() in order to add a new command to the queue of at-jobs. Use the methods list() and load() to get a list of all registered jobs or to load a specific job given an ID, respectively. The module uses time stamps in seconds for scheduling jobs.

univention.lib.atjobs.add(cmd, execTime=None, comments={})[source]

Add a new command to the job queue given a time at which the job will be executed.

Parameters:
  • execTime (int or float or datetime.datetime or None) – execution time either as seconds since the epoch or as a datetime.datetime instance. Defaults to now.
  • comments (dict) – A optional dictionary with comments to be associated with the job.
Returns:

The created job or None.

Return type:

AtJob or None

univention.lib.atjobs.reschedule(nr, execTime=None)[source]

Re-schedules the at job with the given number for the specified time.

Parameters:
  • nr (int) – The job number.
  • execTime (int or float or datetime.datetime or None) – execution time either as seconds since the epoch or as a datetime.datetime instance. Defaults to now.
Returns:

The created job or None.

Return type:

AtJob or None

Raises:

AttributeError: if the job cannot be found.

univention.lib.atjobs.list(extended=False)[source]

Returns a list of all registered jobs.

Parameters:extended (bool) – If set to True also the comments and the command to execute are fetched.
Returns:A list of AtJob instances.
Return type:list[AtJob]

This can be used to re-schedule a job.

univention.lib.atjobs.load(nr, extended=False)[source]

Load the job given.

Parameters:
  • nr – Job number.
  • extended (bool) – If set to True also the comments and the command to execute are fetched.
Returns:

None if job does not exist, otherwise an instance of AtJob.

Return type:

AtJob

univention.lib.atjobs.remove(nr)[source]

Removes the at job with the given number.

Parameters:nr (int) – Job number.
class univention.lib.atjobs.AtJob(nr, owner, execTime, isRunning)[source]

Bases: object

This class is an abstract representation of an at-job. Do not initiate the class directly, but use the methods provided in this module.

Parameters:
  • nr (int) – Job number.
  • owner (str) – User owning the job.
  • execTime (datetime.datetime) – Planned job execution time.
  • isRunning (bool) – True is the jub is currently running, False otherwise.
rm()[source]

Remove the job from the queue.

univention.lib.error module

Functions for handling Python errors.

univention.lib.error.formatTraceback()[source]

Return complete Python traceback as list:

Returns:The traceback as a list of lines.
Return type:list[str]

Call this function directly in the except-clause.

Deprecated since version 4.4: use traceback.format_exc() instead

univention.lib.fstab module

Read and write /etc/fstab.

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

Bases: list

Handle lines of /etc/fstab.

Parameters:file (str) – The name of the file.
_is_comment()

search(string[, pos[, endpos]]) –> match object or None. Scan through string looking for a match, and return a corresponding match object instance. Return None if no position in the string matches.

_filesystems = ('ext2', 'xfs', 'nfs', 'proc', 'auto', 'swap')
load()[source]

Load entries from file.

find(**kargs)[source]

Search and return the entry matching the criteria.

Parameters:kwargs – A mapping of Entry attributes to values.
Returns:The first entry matching all criteria or None.
Return type:Entry or None
get(filesystem=[], ignore_root=True)[source]

Return list of entries matching a list of file system types.

Parameters:
  • filesystem (List[str]) – A list of file system names.
  • ignore_root (bool) – Skip the root file system if True.
Returns:

A list of matching entries.

Return type:

List[Entry]

save()[source]

Save entries to file.

_File__parse(line)

Parse file system table line.

  1. fs_spec
  2. fs_file
  3. fs_vfstype
  4. fs_mntops
  5. fs_freq
  6. fs_passno
Parameters:line (str) – A line.
Returns:The parsed entry.
Return type:Entry
Raises:InvalidEntry – if the line cannot be parsed.
class univention.lib.fstab.Entry(spec, mount_point, type, options, dump=0, passno=0, comment='')[source]

Bases: object

Entry of fstab(5).

Parameters:
  • spec (str) – This field describes the block special device or remote filesystem to be mounted.
  • mount_point (str) – This field describes the mount point (target) for the filesystem.
  • type (str) – The type of the filesystem.
  • options (List[str]) – The list of mount options associated with the filesystem.
  • dump (int) – Option for dump(8).
  • passno (int) – Order information for fsck(8).
  • comment (str) – Optional comment from end of line.
Variables:

uuid (str) – The file system UUID if the file system is mounted by it. Otherwise None.

exception univention.lib.fstab.InvalidEntry[source]

Bases: exceptions.Exception

Invalid entry in file system table

univention.lib.getMailFromMailOrUid module

get primaryMailAddress and uid from primaryMailAddress or uid (used by horde/imp login hook to map uid to mail address)

univention.lib.getMailFromMailOrUid.main()[source]

univention.lib.i18n module

Internationalization (i18n) utilities.

exception univention.lib.i18n.I18N_Error[source]

Bases: exceptions.Exception

Error in Internationalization.

class univention.lib.i18n.Locale(locale=None)[source]

Bases: object

Represents a locale specification and provides simple access to language, territory, codeset and modifier.

Parameters:locale (str or None) – The locale string language[_territory][.codeset][@modifier].
REGEX = <_sre.SRE_Pattern object>
parse(locale)[source]

Parse locale string.

Parameters:

locale (str) – The locale string language[_territory][.codeset][@modifier].

Raises:
  • TypeError – if locale is not a string.
  • I18N_Error – if locale does not match the format.
_Locale__reset()
class univention.lib.i18n.NullTranslation(namespace, locale_spec=None, localedir=None)[source]

Bases: object

Dummy translation.

Parameters:
  • namespace (str) – The name of the translation domain.
  • locale_spec (str) – The selected locale.
  • localedir (str) – The name of the directory containing the translation files.
_set_domain(namespace)[source]

Select translation domain.

Parameters:namespace (str) – The name of the translation domain.
domain
set_language(language=None)[source]

Select language.

Parameters:language (str) – The language code.
_get_locale()[source]

Return currently selected locale.

Returns:The currently selected locale.
Return type:Locale
_set_locale(locale_spec=None)[source]

Select new locale.

Parameters:locale_spec (str) – The new locale specification.
locale

Return currently selected locale.

Returns:The currently selected locale.
Return type:Locale
translate(message)[source]

Translate message.

Parameters:message (str) – The message to translate.
Returns:The localized message.
Return type:str
_(message)

Translate message.

Parameters:message (str) – The message to translate.
Returns:The localized message.
Return type:str
class univention.lib.i18n.Translation(namespace, locale_spec=None, localedir=None)[source]

Bases: univention.lib.i18n.NullTranslation

Translation.

locale = <univention.lib.i18n.Locale object>
set_language(language=None)[source]

Select language.

Parameters:language (str) – The language code.
Raises:I18N_Error – if the given locale is not valid.

univention.lib.ldap_extension module

Python function to register UDM extensions in LDAP.

exception univention.lib.ldap_extension.BaseDirRestriction[source]

Bases: exceptions.Exception

class univention.lib.ldap_extension.UCSOption(*opts, **attrs)[source]

Bases: optparse.Option

TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice', 'existing_filename', 'ucs_version')
TYPE_CHECKER = {'int': <function check_builtin>, 'float': <function check_builtin>, 'ucs_version': <function option_validate_ucs_version>, 'long': <function check_builtin>, 'choice': <function check_choice>, 'complex': <function check_builtin>, 'gnu_message_catalogfile': <function option_validate_gnu_message_catalogfile>, 'existing_filename': <function option_validate_existing_filename>}
class univention.lib.ldap_extension.UniventionDataExtension(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionLDAPExtension

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
active_flag_attribute = ''
filesuffix = ''
is_local_active()[source]
target_container_name = 'data'
udm_module_name = 'settings/data'
wait_for_activation(timeout=180)[source]
class univention.lib.ldap_extension.UniventionLDAPACL(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionLDAPExtensionWithListenerHandler

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
_handler(dn, new, old, name=None)[source]

Handle LDAP ACL extensions on Master, Backup and Slave

active_flag_attribute = 'univentionLDAPACLActive'
file_prefix = 'ldapacl_'
filesuffix = '.acl'
handler(dn, new, old, name=None)[source]
target_container_name = 'ldapacl'
udm_module_name = 'settings/ldapacl'
class univention.lib.ldap_extension.UniventionLDAPExtension(ucr)[source]

Bases: object

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
active_flag_attribute
classmethod create_base_container(ucr, udm_passthrough_options)[source]
filesuffix
is_local_active()[source]
mark_active(handler_name=None)[source]
register(filename, options, udm_passthrough_options, target_filename=None)[source]
target_container_name
udm_find_object()[source]
udm_find_object_dn()[source]
udm_module_name
unregister(objectname, options, udm_passthrough_options)[source]
wait_for_activation(timeout=180)[source]
class univention.lib.ldap_extension.UniventionLDAPExtensionWithListenerHandler(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionLDAPExtension

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
handler(dn, new, old, name=None)[source]
class univention.lib.ldap_extension.UniventionLDAPSchema(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionLDAPExtensionWithListenerHandler

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
_handler(dn, new, old, name=None)[source]

Handle LDAP schema extensions on Master and Backup

active_flag_attribute = 'univentionLDAPSchemaActive'
basedir = '/var/lib/univention-ldap/local-schema'
filesuffix = '.schema'
handler(dn, new, old, name=None)[source]
target_container_name = 'ldapschema'
udm_module_name = 'settings/ldapschema'
class univention.lib.ldap_extension.UniventionUDMExtension(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionLDAPExtension

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
wait_for_activation(timeout=180)[source]
class univention.lib.ldap_extension.UniventionUDMHook(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionUDMExtension

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
active_flag_attribute = 'univentionUDMHookActive'
filesuffix = '.py'
target_container_name = 'udm_hook'
udm_module_name = 'settings/udm_hook'
class univention.lib.ldap_extension.UniventionUDMModule(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionUDMExtension

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
active_flag_attribute = 'univentionUDMModuleActive'
filesuffix = '.py'
register(filename, options, udm_passthrough_options, target_filename=None)[source]
target_container_name = 'udm_module'
udm_module_name = 'settings/udm_module'
class univention.lib.ldap_extension.UniventionUDMSyntax(ucr)[source]

Bases: univention.lib.ldap_extension.UniventionUDMExtension

_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
active_flag_attribute = 'univentionUDMSyntaxActive'
filesuffix = '.py'
target_container_name = 'udm_syntax'
udm_module_name = 'settings/udm_syntax'
univention.lib.ldap_extension._get_handler_message_object(lo, position, handler_name, create=False)[source]
univention.lib.ldap_extension._verify_handler_message_container(lo, position)[source]
univention.lib.ldap_extension.check_data_module_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.check_udm_hook_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.check_udm_module_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.check_udm_syntax_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.get_handler_message(name, binddn, bindpw)[source]
univention.lib.ldap_extension.option_callback_append_data_module_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.option_callback_append_udm_hook_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.option_callback_append_udm_module_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.option_callback_append_udm_syntax_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.option_callback_set_data_module_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.option_callback_set_udm_module_options(option, opt_str, value, parser)[source]
univention.lib.ldap_extension.option_callback_udm_passthrough_options(option, opt_str, value, parser, *args)[source]
univention.lib.ldap_extension.option_validate_existing_filename(option, opt, value)[source]
univention.lib.ldap_extension.option_validate_gnu_message_catalogfile(option, opt, value)[source]
univention.lib.ldap_extension.option_validate_ucs_version(option, opt, value)[source]
univention.lib.ldap_extension.safe_path_join(basedir, filename)[source]
univention.lib.ldap_extension.set_handler_message(name, dn, msg)[source]
univention.lib.ldap_extension.ucs_registerLDAPExtension()[source]
univention.lib.ldap_extension.ucs_unregisterLDAPExtension()[source]

univention.lib.license_tools module

exception univention.lib.license_tools.LicenseCheckError[source]

Bases: exceptions.Exception

Generic error during license check

exception univention.lib.license_tools.LicenseExpired[source]

Bases: univention.lib.license_tools.LicenseCheckError

The license is expired

exception univention.lib.license_tools.LicenseNotFound[source]

Bases: univention.lib.license_tools.LicenseCheckError

The license cannot be found in LDAP

univention.lib.license_tools.is_CSP_license(lo=None)[source]

Function to detect if installed license is a cloud service provider license (CSP).

Parameters:

lo (univention.uldap.acceess) – Optional LDAP connection to re-use. Otherwise a new LDAP connection with machine credentials is created.

Returns:

True if a valid CSP license has been found or False if a valid non-CSP license has been found.

Raises:
  • LicenseNotFound – if no license was found.
  • LicenseExpired – if the license has expired.

univention.lib.listenerSharePath module

Univention Helper functions for creating or renaming share directories

univention.lib.listenerSharePath.dirIsMountPoint(path)[source]

Check if path is a mount point.

Parameters:path (str) – The path to check.
Returns:A string if the path is a mount point, None otherwise.
Return type:str or None
univention.lib.listenerSharePath.checkDirFileSystem(path, cr)[source]

Check if the given path is of a known file system type.

Parameters:
Returns:

A string if the path is a known file system, None otherwise.

Return type:

str or None

univention.lib.listenerSharePath.createOrRename(old, new, cr)[source]

Create or rename a share.

Parameters:
Returns:

A string if an error occurs, None on success.

Return type:

str or None

univention.lib.listenerSharePath.is_blacklisted(path, ucr)[source]
>>> is_blacklisted('/home/', {})
True
>>> is_blacklisted('/home/', {'listener/shares/whitelist/default': '/home/*:/var/*'})
False
>>> is_blacklisted('/home', {})
True
>>> is_blacklisted('/home', {'listener/shares/whitelist/default': '/home/*:/var/*'})
False
>>> is_blacklisted('/home/Administrator', {})
True
>>> is_blacklisted('/home/Administrator', {'listener/shares/whitelist/default': '/home/*:/var/*'})
False
>>> is_blacklisted('/home/Administrator/', {'listener/shares/whitelist/admin': '/home/Administrator'})
False

univention.lib.locking module

Univention Common Python Library for file locking

univention.lib.locking.get_lock(name, nonblocking=False)[source]

Get a exclusive lock.

Parameters:
  • name (str) – The name for the lock file.
  • nonblocking (bool) – Return None instead of waiting indefinitely to get the exclusive lock if the lock is already taken.
Returns:

a file descriptor for a lock file after the file has been locked exclusively. In non-blocking mode None is returned if the lock cannot be gained.

Return type:

file or None

The returned file descriptor has to be kept. Otherwise the lock will be release automatically on file descriptor’s destruction.

>>> fd = get_lock('myapp')
>>> # ...... do some critical stuff ......
>>> release_lock(fd)
>>>
>>> fd = get_lock('myapp', nonblocking=True)
>>> if not fd:
>>>     print('cannot get lock')
>>> else:
>>>     # ...... do some critical stuff ......
>>>     release_lock(fd)
univention.lib.locking.release_lock(fd)[source]

Releases the previously gained lock.

Parameters:fd (file) – The file descriptor of the lock file.

univention.lib.misc module

Univention Common Python Library

univention.lib.misc.createMachinePassword()[source]

Returns a $(pwgen) generated password according to the requirements in UCR variables machine/password/length and machine/password/complexity.

Returns:A password.
Return type:str
univention.lib.misc.getLDAPURIs(configRegistryInstance=None)[source]

Returns a space separated list of all configured LDAP servers, according to UCR variables ldap/server/name and ldap/server/addition.

Parameters:configRegistryInstance (univention.config_registry.ConfigRegistry) – An optional UCR instance.
Returns:A space separated list of LDAP URI.
Return type:str
univention.lib.misc.getLDAPServersCommaList(configRegistryInstance=None)[source]

Returns a comma-separated string with all configured LDAP servers, ldap/server/name and ldap/server/addition.

Parameters:configRegistryInstance (univention.config_registry.ConfigRegistry) – An optional UCR instance.
Returns:A space separated list of LDAP host names.
Return type:str
univention.lib.misc.custom_username(name, configRegistryInstance=None)[source]

Returns the customized user name configured via UCR.

Parameters:
  • name (str) – A user name.
  • configRegistryInstance (univention.config_registry.ConfigRegistry) – An optional UCR instance.
Returns:

The translated user name.

Return type:

str

Raises:

ValueError – if no name is given.

univention.lib.misc.custom_groupname(name, configRegistryInstance=None)[source]

Returns the customized group name configured via UCR.

Parameters:
  • name (str) – A group name.
  • configRegistryInstance (univention.config_registry.ConfigRegistry) – An optional UCR instance.
Returns:

The translated group name.

Return type:

str

Raises:

ValueError – if no name is given.

univention.lib.ordered_set module

class univention.lib.ordered_set.OrderedSet(iterable=None)[source]

Bases: _abcoll.MutableSet

A set() that remembers insertion order.

_name
add(key)[source]
update(sequence)[source]
clear()[source]
pop()[source]
discard(key)[source]
isdisjoint(other)[source]
issubset(other)[source]
issuperset(other)[source]
difference(other)[source]
intersection(other)[source]
symmetric_difference(other)[source]
union(other)[source]
_abc_cache = <_weakrefset.WeakSet object>
_abc_negative_cache = <_weakrefset.WeakSet object>
_abc_negative_cache_version = 34
_abc_registry = <_weakrefset.WeakSet object>
class univention.lib.ordered_set.OrderedSetTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.

test_empty_init()[source]
test_simple_init()[source]
test_large_init()[source]
test_contains()[source]
test_getitem()[source]
test_add()[source]
test_update()[source]
test_clear()[source]
test_pop()[source]
test_discard()[source]
test_iter()[source]
test_eq_empty()[source]
test_eq_single()[source]
test_eq_multiple()[source]
test_reversed()[source]
test_remove()[source]
test_is_subset()[source]
test_is_superset()[source]
test_union()[source]
test_union_set()[source]
test_intersection()[source]
test_intersection_set()[source]
test_difference()[source]
test_difference_set()[source]
test_symmetric_difference()[source]
test_symmetric_difference_set()[source]

univention.lib.package_manager module

Univention common Python Library for package management (info/install/progress...)

exception univention.lib.package_manager.LockError[source]

Bases: exceptions.Exception

Lock error for the package manager. Not to be confused with LockFailedException

class univention.lib.package_manager.ProgressState(parent_logger)[source]

Bases: object

Track APT progress and report.

Parameters:parent_logger (logging.Logger) – The Logger of the parent.
reset()[source]

Reset minimal progress state.

hard_reset()[source]

Reset full progress state.

set_finished()[source]

Mark installation as finished.

get_logger(logger_name=None)[source]

Return (sub-)logger.

Parameters:logger_name (str) – The optional name for the sub-logger. If not given, the shared logger of the manager is used.
Returns:A Logger instance.
Return type:logging.Logger
info(info, logger_name=None)[source]

Log info message.

Parameters:
  • info (str) – The info message to log.
  • logger_name (str) – The optional name for the sub-logger. If not given, the shared logger of the manager is used.
percentage(percentage, logger_name='percentage')[source]

Update progress information.

Parameters:
  • percentage (float) – The percentage of completeness.
  • logger_name (str) – The optional name for the sub-logger. If not given, the shared logger of the manager is used.
error(error, logger_name=None)[source]

Log error message.

Parameters:
  • error (str) – The error message to log.
  • logger_name (str) – The optional name for the sub-logger. If not given, the shared logger of the manager is used.
add_start_steps(steps)[source]

Add additional planned steps.

Parameters:steps (int) – The number of additional steps to add.
_steps

Return progress as step counter

Returns:A percentage value, which might be >100%
Return type:float
poll()[source]

Return the aggregated state. The state is reset afterwards using reset().

Returns:A dictionary containing the last info and error message, number of steps and finished state.
Return type:dict
class univention.lib.package_manager.MessageWriter(progress_state)[source]

Bases: object

Mimics a file() object supports flush() and write(). Writes no ‘r’, writes no empty strings, writes not just spaces. If it writes it is handled by progress_state.

Parameters:progress_state (ProgressState) – Instance which is responsible for collecting the state.
flush()[source]

Dummy function to flush all pending writes.

write(msg)[source]

Write sanitized message to the state collector.

Parameters:msg (str) – The message to write.
class univention.lib.package_manager.FetchProgress(outfile=None)[source]

Bases: sphinx.ext.autodoc.AcquireProgress

Used to handle information about fetching packages. Writes a lot of __MSG__`es, as it uses :py:class:`MessageWriter.

Parameters:outfile (ProgressState) – An instance to receive the progress information.
start()[source]

Start collection progress information.

_write(msg, newline=True, maximize=True)[source]

Write message.

Parameters:
  • msg (str) – The message to write.
  • newline (bool) – Append trailing newline.
  • maximize (bool) – resize to terminal width.
class univention.lib.package_manager.DpkgProgress(progress_state)[source]

Bases: sphinx.ext.autodoc.InstallProgress

Report progress when installing or removing software. Writes messages (and percentage) from APT status file descriptor

fork()[source]

Fork a child process for calling APT and setup pipes for progress reporting. The parent process will also start a Thread for reading the pipe.

Returns:The process identifier: 0 for the child, != 0 for the parent process.
Return type:int
check_pipe(pipe_read)[source]

Internal function for reading the pipe and updating the progress status.

Parameters:read (file) – The pipe to read.
status_change(pkg, percent, status)[source]

Update installation status and progress.

Parameters:
  • pkg (str) – The currently process package name.
  • percent (float) – The progress.
  • status (str) – The status message.
error(pkg, errormsg)[source]

Report an error.

Parameters:
  • pkg (str) – The name of the binary package currently being processed.
  • errormsg (str) – An error message.
class univention.lib.package_manager._PackageManagerLoggerHandler(info_handler, step_handler, error_handler)[source]

Bases: logging.Handler

Translate Python logging events to separate handlers.

Parmm info_handler:
 A optional function which accepts info messages as the single argument.
Parmm step_handler:
 A optional function which accepts step messages as the single argument.
Parmm error_handler:
 A optional function which accepts error messages as the single argument.
emit(record)[source]

Translate event to calls of APT handlers. :param logging.LogRecord event: An event.

class univention.lib.package_manager.PackageManager(lock=True, info_handler=None, step_handler=None, error_handler=None, always_noninteractive=True)[source]

Bases: object

High-level package manager for UCS.

Parameters:
  • lock (bool) – Get an exclusive lock to prevent other instances from running in parallel.
  • info_handler – Some handler to handle info messages.
  • step_handler – Some handler to handle progress messages.
  • error_handler – Some handler to handle error messages.
  • always_noninteractive – Run dpkg in non-interactive mode to prevent any user input.
always_install(pkgs=None, just_mark=False)[source]

Set packages that should be installed and never uninstalled. If you overwrite old always_install, make sure to call reopen_cache().

Parameters:
  • pkgs (list) – The list of packages to .
  • just_mark (bool) – if True, process the previously saved list of packages instead of the given new list.
lock(raise_on_fail=True)[source]

Get locks to prevent concurrent calls.

Parameters:raise_on_fail (bool) – Raise LockError instead of returning False.
Returns:True if all locks were are acquired, False otherwise.
Return type:bool
Raises:LockError – if the lock cannot be acquired.
unlock()[source]

Release locks.

Returns:True if the manager lock was taken, False otherwise.
Return type:bool
is_locked()[source]

Return the state of the lock.

Returns:True if the lock is acquired, False otherwise.
Return type:bool
locked(*args, **kwds)[source]

Perform locking and cleanup actions before and after working with package state.

Parameters:
_shell_command(command, handle_streams=True)[source]

Execute command processing and returning its output.

Parameters:
  • command (list) – The command to execute.
  • handle_streams (bool) – Pass stdout and stderr to registered progress handler.
Returns:

a 2-tuple (stdout, stderr)

Return type:

tuple(str, str)

no_umc_restart(*args, **kwds)[source]

Run package manager with restart of UMC (and Apache) disabled.

Parameters:exclude_apache (bool) – If True Apache may be restarted.
_set_apt_pkg_config(options)[source]

Set APT options.

Parameters:options (list[tuple[str, str]]) – A list of 2-tuples (name, value)
Returns:A list of 2-tuples (name, old-value)
Return type:list[tuple[str, str]]
add_hundred_percent()[source]

Add another 100 steps.

set_max_steps(steps)[source]

Set maximum number of steps.

Parameters:steps (int) – Number of steps.
set_finished()[source]

Signal all steps done.

poll(timeout)[source]

Poll for progress.

Parameters:timeout – Ignored
Returns:A dictionary containing the last info and error message, number of steps and finished state.
Return type:dict
reset_status()[source]

Reset progress indicator back to start.

brutal_noninteractive(*args, **kwds)[source]

Configure package manager to never ask for user input and to overwrite changed files

noninteractive(*args, **kwds)[source]

Configure package manager to never ask for user input.

update()[source]

apt-get update

Returns:True on success, `False otherwise.
Return type:bool
get_packages(pkg_names)[source]

Get many Package-objects at once (only those that exist, write error for others)

Parameters:pkg_names – A list of binary package names.
Returns:A list of APT cache entries.
get_package(pkg_name, raise_key_error=False)[source]

Get Package-object for package name.

Parameters:
  • pkg_name (str) – A binary package name.
  • raise_key_error – Raise error when True, otherwise write an error message.
Returns:

The APT cache entry for the binary package.

is_installed(pkg_name, reopen=False)[source]

Returns whether a package is installed.

Parameters:
  • pkg_name (str) – A binary package name.
  • reopen (bool) – Re-open the APT cache before checking.
Returns:

True if installed, False if not, and None if package is not found.

packages(reopen=False)[source]

Yields all packages in cache.

Parameters:reopen (bool) – Re-open the APT cache before returning.
mark_auto(auto, *pkgs)[source]

Immediately sets packages to automatically installed (or not).

Parameters:
  • auto (bool) – Mark the packages as automatically installed (True) or not.
  • pkgs – A list of binary package names.

Calls commit()!

mark(install, remove, dry_run=False)[source]

Mark packages as automatically installed (or not).

Parameters:
  • install – A list of packages to install.
  • remove – A list of packages to remove.
  • dry_run (bool) – Only simulate the action if True.
Returns:

A 3-tuple (to_be_installed, to_be_removed, broken), where each argument is a list of package names.

commit(install=None, remove=None, upgrade=False, dist_upgrade=False, msg_if_failed='')[source]

Really commit changes (mark_install or mark_delete) or pass Package-objects that shall be committed. Never forgets to pass progress objects, may print error messages, always reopens cache.

Parameters:
  • install – List of package names to install.
  • remove – List of package names to remove.
  • upgrade – Perform upgrade were no new packages are installed.
  • dist_upgrade – Perform upgrade were new packages may be installed and old packages may be removed.
  • msg_if_failed – Test message to output if things go wrong.
Returns:

True on success, False otherwise.

reopen_cache()[source]

Reopen the APT cache.

Has to be done when the APT database changed.

_open_cache()[source]

Internal function to (re-)open the APT cache.

_handle_system_error(etype, exc, etraceback)[source]

Log exception from opening APT cache.

Parameters:
  • etype (type) – Exception type.
  • exc (BaseException) – Exception instance.
  • etraceback – Exception traceback.
_get_error_message(exc)[source]

Parse exception message and return standardized messages for user consumption.

Parameters:exc (BaseException) – An exception instance.
Returns:A list of translated messages.

All strings which must pass this function are in: <https://forge.univention.org/bugzilla/attachment.cgi?id=6898>

autoremove()[source]

Remove all packages which are no longer required.

It seems that there is nothing like self.cache.autoremove.

upgrade()[source]

Instantly performs an apt-get upgrade.

Returns:True on success, False otherwise.
dist_upgrade()[source]

Instantly performs an apt-get dist-upgrade.

Returns:True on success, False otherwise.
install(*pkg_names)[source]

Instantly installs packages when found. Works like apt-get install and apt-get upgrade.

Parameters:pkg_names – A list of binary package names to install.
Returns:True on success, False otherwise.
uninstall(*pkg_names)[source]

Instantly deletes packages when found.

Parameters:pkg_names – A list of binary package names to remove.
Returns:True on success, False otherwise.

univention.lib.password module

univention.lib.password.change(username, password)[source]

Change the password of the given user

>>> import univention.lib.password
>>> univention.lib.password.change('Administrator', 'secret12345')
>>> univention.lib.password.change('Administrator@DOMAIN.DE', 'secret12345')
>>>

univention.lib.policy_result module

univention.lib.policy_result.policy_result(dn, binddn='', bindpw='')[source]

Return a tuple of hash-lists, mapping attributes to a list of values and mapping attributes to the matching Policy-DN.

>>> (results, policies) = policy_result('dc=opendvdi,dc=local', [binddn=BINDDN, bindpw=BINDPW])
>>> policies['univentionDhcpDomainNameServers']
'cn=default-settings,cn=dns,cn=dhcp,cn=policies,dc=opendvdi,dc=local'
results['univentionDhcpDomainNameServers']
['192.168.0.111']

univention.lib.s4 module

Univention common Python Library for common AD constants.

univention.lib.s4.well_known_sids = {'S-1-5-32-545': 'Users', 'S-1-5-32-544': 'Administrators', 'S-1-5-32-547': 'Power Users', 'S-1-5-32-546': 'Guests', 'S-1-5-32-551': 'Backup Operators', 'S-1-5-32-557': 'Incoming Forest Trust Builders', 'S-1-5-32-568': 'IIS_IUSRS', 'S-1-5-32-552': 'Replicator', 'S-1-5-32-549': 'Server Operators', 'S-1-3-3': 'Creator Group Server', 'S-1-3-2': 'Creator Owner Server', 'S-1-2-0': 'Local', 'S-1-2-1': 'Console Logon', 'S-1-5-32-554': 'Pre-Windows 2000 Compatible Access', 'S-1-5-32-548': 'Account Operators', 'S-1-5-32-559': 'Performance Log Users', 'S-1-5-32-561': 'Terminal Server License Servers', 'S-1-5-80-0': 'All Services', 'S-1-5-32-556': 'Network Configuration Operators', 'S-1-5-32-555': 'Remote Desktop Users', 'S-1-5-32-573': 'Event Log Readers', 'S-1-5-32-569': 'Cryptographic Operators', 'S-1-3': 'Creator Authority', 'S-1-2': 'Local Authority', 'S-1-5': 'NT Authority', 'S-1-4': 'Non-unique Authority', 'S-1-5-32-560': 'Windows Authorization Access Group', 'S-1-5-32-574': 'Certificate Service DCOM Access', 'S-1-5-1': 'Dialup', 'S-1-5-32-562': 'Distributed COM Users', 'S-1-5-32-558': 'Performance Monitor Users', 'S-1-5-32-550': 'Print Operators'}

Well known security identifiers.

univention.lib.s4.well_known_domain_rids = {'521': 'Read-Only Domain Controllers', '516': 'Domain Controllers', '515': 'Domain Computers', '571': 'Allowed RODC Password Replication Group', '553': 'RAS and IAS Servers', '519': 'Enterprise Admins', '518': 'Schema Admins', '520': 'Group Policy Creator Owners', '517': 'Cert Publishers', '522': 'Cloneable Domain Controllers', '572': 'Denied RODC Password Replication Group', '498': 'Enterprise Read-only Domain Controllers', '513': 'Domain Users', '512': 'Domain Admins', '502': 'KRBTGT', '514': 'Domain Guests', '500': 'Administrator', '501': 'Guest'}

Mapping of well known relative (security) identifiers to their (English) names.

See rids_for_well_known_security_identifiers for the reverse mapping.

univention.lib.s4.rids_for_well_known_security_identifiers = {'administrator': '500', 'guest': '501', 'enterprise admins': '519', 'domain users': '513', 'krbtgt': '502', 'domain guests': '514', 'schema admins': '518', 'allowed rodc password replication group': '571', 'group policy creator owners': '520', 'denied rodc password replication group': '572', 'enterprise read-only domain controllers': '498', 'read-only domain controllers': '521', 'ras and ias servers': '553', 'cloneable domain controllers': '522', 'domain controllers': '516', 'cert publishers': '517', 'domain computers': '515', 'domain admins': '512'}

Mapping of lower cases English names to to well known relative (security) identifiers.

See well_known_domain_rids for the reverse mapping.

univention.lib.share_restrictions module

class univention.lib.share_restrictions.Restrictions(name)[source]

Bases: dict

INVALID_USERS = 'invalid users'
VALID_USERS = 'valid users'
HOSTS_DENY = 'hosts deny'
HOSTS_ALLOW = 'hosts allow'
_add(key, value)[source]
invalid_users
valid_users
hosts_deny
hosts_allow
class univention.lib.share_restrictions.Share(name)[source]

Bases: univention.lib.share_restrictions.Restrictions

class univention.lib.share_restrictions.Printer(name)[source]

Bases: univention.lib.share_restrictions.Restrictions

smbname
class univention.lib.share_restrictions.ShareConfiguration[source]

Bases: object

SHARES_DIR = '/etc/samba/local.config.d'
SHARES_UDM_DIR = '/etc/samba/shares.conf.d'
PRINTERS_UDM_DIR = '/etc/samba/printers.conf.d'
POSTFIX = '.local.config.conf'
PREFIX = 'printer.'
INCLUDE_CONF = '/etc/samba/local.config.conf'
GLOBAL_CONF = '/etc/samba/local.config.d/global.local.config.conf'
CUPS_CONF = '/etc/cups/printers.conf'
delete()[source]

delete all conf’s in SHARES_DIR and INCLUDE_CONF

read_shares()[source]

get invalid user from samba share conf

read_printers()[source]

get invalid/valid users from cups and samba config

_set_invalids(value, share, group)[source]
_set_denied_hosts(value, share)[source]
_set_printmode_group(mode, group)[source]
_set_printmode_hosts(hosts, mode)[source]
_set_othershares(value, group)[source]

append group to invalid users for all shares, except shares group (the groupname) and marktplatz

_set_othershares_hosts(value)[source]
_set_globals(value, option)[source]
_set_options(value, share, option)[source]
read_ucr()[source]
read()[source]
write()[source]
globals
shares
printers

univention.lib.shell module

Univention common Python library for shell scripts.

univention.lib.shell.escape_value(value)[source]

Escape a value for shell usage with double quotes.

Parameters:value (str) – The string to escape.
Returns:The escaped string.
Return type:str

Deprecated since version 4.4: use pipes.quote() instead

>>> escape_value('eins zwei')
'"eins zwei"'
>>> escape_value('''"'$\`''')
'"\\"\'\\$\\\\\\`"'
univention.lib.shell.create_at_job(script, time=None, date=None)[source]

Create an at job.

Parameters:
  • script (List[str] or Tuple[str] or str) – The shell command to execute.
  • time (str) – The time of day when the command is to be executed. If None is given, now is used.
  • date (str) – The date when the command is to be executed.
Returns:

an AtJob object with the named attributes .returncode, .job, .stdout and .stderr.

>>> r = create_at_job('''echo "42"''')
>>> r = create_at_job(['echo', 'noon'], '12:00')
>>> r = create_at_job(['echo', 'new year'], '24:00', '31.12.2030')
>>> (r.returncode, r.job, r.stdout, r.stderr) 
(0, ..., '', '...job ... at Wed Jan  1 00:00:00 2031\n')

Deprecated since version 4.4.

See univention.atjobs for an alternative implementation.

univention.lib.ucrLogrotate module

Univention common Python library for logrotate configuration files.

univention.lib.ucrLogrotate._getBoolDefault(varGlobal, varLocal, settings, configRegistry)[source]

Get default value of type boolean.

Parameters:
  • varGlobal (str) – The UCR variable name of the global setting.
  • varLocal (str) – The UCR variable name of the service specific setting.
  • settings (dict) – A mapping, where the configuration is stored in.
  • configRegistry (ConfigRegistry) – An UCR instance.
univention.lib.ucrLogrotate.getLogrotateConfig(name, configRegistry)[source]

Build aggregated configuration for log file rotation.

Parameters:
  • name (str) – The name of the log file or service.
  • configRegistry (ConfigRegistry) – An UCR instance.
Returns:

A dictionary containing the merged configuration.

Return type:

dict

>>> ucr = ConfigRegistry()
>>> ucr.load()
>>> conf = getLogrotateConfig('service', ucr)

univention.lib.ucs module

UCS release version.

class univention.lib.ucs.UCS_Version(version)[source]

Bases: object

Version object consisting of major-, minor-number and patch-level

Parameters:version (list(int) or tuple(int) or str or UCS_Version) – must a str matching the pattern X.Y-Z or a triple with major, minor and patchlevel.
Raises:TypeError – if the version cannot be parsed.
>>> v = UCS_Version((2,3,1))
>>> UCS_Version([2,3,1]) == v
True
>>> UCS_Version("2.3-1") == v
True
>>> UCS_Version(v) == v
True
FORMAT = '%(major)d.%(minor)d'
FULLFORMAT = '%(major)d.%(minor)d-%(patchlevel)d'
_regexp = <_sre.SRE_Pattern object>
mm

2-tuple (major, minor) version

mmp

3-tuple (major, minor, patch-level) version

set(version)[source]

Parse string and set version.

Parameters:version (str) – A UCS release version string.
Raises:ValueError – if the string is not a valid UCS release version string.

univention.lib.umc module

Univention common Python library to manage connections to remote UMC servers

>>> umc = Client()
>>> umc.authenticate_with_machine_account()
>>> response = umc.umc_get('session-info')
>>> response.status
200
>>> response = umc.umc_logout()
>>> response.status
303
class univention.lib.umc._HTTPType(mcs, name, bases, dict)[source]

Bases: type

Metaclass for HTTP Error exceptions. Sub-classes of this meta class are automatically added to the HTTPError.codes mapping.

exception univention.lib.umc.ConnectionError(msg, reason=None)[source]

Bases: exceptions.Exception

Signal an error during connection setup.

Parameters:
  • msg (str) – A message string.
  • reason – The optional underlying exception.
exception univention.lib.umc.HTTPError(request, response, hostname)[source]

Bases: exceptions.Exception

Base class for HTTP errors. A specialized sub-class if automatically instantiated based on the HTTP return code.

Parameters:
  • request – The HTTP request.
  • response (httplib.HTTPResponse) – The HTTP response.
  • hostname (str) – The host name of the failed server.
codes = {400: <class 'univention.lib.umc.BadRequest'>, 502: <class 'univention.lib.umc.BadGateway'>, 422: <class 'univention.lib.umc.UnprocessableEntity'>, 300: <class 'univention.lib.umc.HTTPRedirect'>, 301: <class 'univention.lib.umc.MovedPermanently'>, 302: <class 'univention.lib.umc.Found'>, 303: <class 'univention.lib.umc.SeeOther'>, 304: <class 'univention.lib.umc.NotModified'>, 401: <class 'univention.lib.umc.Unauthorized'>, 403: <class 'univention.lib.umc.Forbidden'>, 404: <class 'univention.lib.umc.NotFound'>, 405: <class 'univention.lib.umc.MethodNotAllowed'>, 406: <class 'univention.lib.umc.NotAcceptable'>, 503: <class 'univention.lib.umc.ServiceUnavailable'>, 500: <class 'univention.lib.umc.InternalServerError'>}

Specialized sub-classes for individual HTTP error codes.

status

Return the HTTP status code.

Returns:the numerical status code.
Return type:int
message

Return the HTTP status message.

Returns:the textual status message.
Return type:str
result

Return the HTTP result.

Returns:the result data
Return type:str
exception univention.lib.umc.HTTPRedirect(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.MULTIPLE_CHOICES HTTP/1.1, RFC 2616, Section 10.3.1

code = 300
exception univention.lib.umc.MovedPermanently(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPRedirect

httplib.MOVED_PERMANENTLY HTTP/1.1, RFC 2616, Section 10.3.2

code = 301
exception univention.lib.umc.Found(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPRedirect

httplib.FOUND HTTP/1.1, RFC 2616, Section 10.3.3

code = 302
exception univention.lib.umc.SeeOther(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPRedirect

httplib.SEE_OTHER HTTP/1.1, RFC 2616, Section 10.3.4

code = 303
exception univention.lib.umc.NotModified(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPRedirect

httplib.NOT_MODIFIED HTTP/1.1, RFC 2616, Section 10.3.5

code = 304
exception univention.lib.umc.BadRequest(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.BAD_REQUEST HTTP/1.1, RFC 2616, Section 10.4.1

code = 400
exception univention.lib.umc.Unauthorized(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.UNAUTHORIZED HTTP/1.1, RFC 2616, Section 10.4.2

code = 401
exception univention.lib.umc.Forbidden(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.UNAUTHORIZED HTTP/1.1, RFC 2616, Section 10.4.4

code = 403
exception univention.lib.umc.NotFound(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.NOT_FOUND HTTP/1.1, RFC 2616, Section 10.4.5

code = 404
exception univention.lib.umc.MethodNotAllowed(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.METHOD_NOT_ALLOWED HTTP/1.1, RFC 2616, Section 10.4.6

code = 405
exception univention.lib.umc.NotAcceptable(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.NOT_ACCEPTABLE HTTP/1.1, RFC 2616, Section 10.4.7

code = 406
exception univention.lib.umc.UnprocessableEntity(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.UNPROCESSABLE_ENTITY WEBDAV, RFC 22518, Section 10.3

code = 422
exception univention.lib.umc.InternalServerError(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.INTERNAL_SERVER_ERROR HTTP/1.1, RFC 2616, Section 10.5.1

code = 500
exception univention.lib.umc.BadGateway(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.BAD_GATEWAY HTTP/1.1, RFC 2616, Section 10.5.3

code = 502
exception univention.lib.umc.ServiceUnavailable(request, response, hostname)[source]

Bases: univention.lib.umc.HTTPError

httplib.SERVICE_UNAVAILABLE HTTP/1.1, RFC 2616, Section 10.5.4

code = 503
class univention.lib.umc.Request(method, path, data=None, headers=None)[source]

Bases: object

The HTTP request.

Parameters:
  • method (str) – GET / POST / PUT / DELETE
  • path (str) – the relative path to /univention/.
  • data (str) – either the raw request payload or some data which must be encoded by get_body()
  • headers (dict) – a mapping of HTTP headers
get_body()[source]

Return the request data.

Returns:encodes data in JSON if Content-Type wants it
Return type:bytes
class univention.lib.umc.Response(status, reason, body, headers, _response)[source]

Bases: object

The HTTP response.

Parameters:
  • status (int) – HTTP status code between 200 and 599.
  • reason (str) – string with the reason phrase e.g. ‘OK’
  • body (str) – the raw response body
  • headers (list) – the response headers as list of tuples
  • _response (httplib.HTTPResponse) – The original HTTP response.
result

Return result from JSON data.

Returns:The result.
message

Return message from JSON data.

Returns:The message.
get_header(name, default=None)[source]

Return original HTTP response header.

Parameters:
  • name (str) – HTTP respone header name, e.g. Content-Type.
  • default – Default value of the header is not set. Defaults to None.
Returns:

The header value or None.

Return type:

str or None

decode_body()[source]

Decode HTTP response and return JSON data as dictionary.

Returns:JSON data is returned as a dictionary, all other as raw.
Return type:dict or str
classmethod _from_httplib_response(response)[source]

Create class instance from HTTP response.

Parameters:response (httplib.HTTPResponse) – The HTTP response.
class univention.lib.umc.Client(hostname=None, username=None, password=None, language=None, timeout=None, automatic_reauthentication=False)[source]

Bases: object

A client capable to speak with a UMC server.

Parameters:
  • hostname (str) – The name of the host to connect. Defaults to the FQDN of the localhost.
  • username (str) – A user name.
  • password (str) – The password of the user.
  • language (str) – The preferred language.
  • timeout (float) – Set the default timeout in seconds (float) for new connections.
  • automatic_reauthentication (bool) – Automatically re-authenticate and re-do requests if the authentication cookie expires.
ConnectionType

alias of HTTPSConnection

authenticate(username, password)[source]

Authenticate against the host and preserves the cookie. Has to be done only once (but keep in mind that the session probably expires after 10 minutes of inactivity)

Parameters:
  • username (str) – A user name.
  • password (str) – The password of the user.
reauthenticate()[source]

Re-authenticate using the stored username and password.

set_basic_http_authentication(username, password)[source]

Setup authentication using HTTP Basic authentication.

Parameters:
  • username (str) – A user name.
  • password (str) – The password of the user.
authenticate_saml(username, password)[source]

Setup authentication using SAML.

Parameters:
  • username (str) – A user name.
  • password (str) – The password of the user.

Warning

not implemented.

authenticate_with_machine_account()[source]

Setup authentication using the machine account.

Raises:ConnectionError – if /etc/machine.secret cannot be read.
umc_command(path, options=None, flavor=None, headers=None)[source]

Perform generic UMC command.

Parameters:
  • path (str) – The URL path of the command after the command/ prefix.
  • options (dict) – The argument for the UMC command.
  • flavor (str) – Optional name of the UMC module flavor, e.g. users/user for UDM modules.
  • headers (dict) – Optional HTTP headers.
Returns:

The UMC response.

Return type:

Response

umc_set(options, headers=None)[source]

Perform UMC set command.

Parameters:
  • options (dict) – The argument for the UMC set command.
  • headers (dict) – Optional HTTP headers.
Returns:

The UMC response.

Return type:

Response

umc_get(path, options=None, headers=None)[source]

Perform UMC get command.

Parameters:
  • path (str) – The URL path of the command after the get/ prefix.
  • options (dict) – The argument for the UMC get command.
  • headers (dict) – Optional HTTP headers.
Returns:

The UMC response.

Return type:

Response

umc_upload()[source]

Perform UMC upload action.

Warning

not implemented.

umc_auth(username, password, **data)[source]

Perform UMC authentication command.

Parameters:
  • username (str) – A user name.
  • password (str) – The password of the user.
  • data – Additional argument for the UMC auth command.
Returns:

The UMC response.

Return type:

Response

umc_logout()[source]

Perform UMC logout action.

Returns:The UMC response.
Return type:Response
request(method, path, data=None, headers=None)[source]

Send request to UMC server handling re-authentication.

Parameters:
  • method (str) – The HTTP method for the request.
  • path (str) – The URL of the request.
  • data – The message body.
  • headers (dict) – Optional HTTP headers.
Returns:

The UMC response.

Return type:

Response

Raises:

Unauthorized – if the session expired and re-authentication was disabled.

send(request)[source]

Low-level function to send request to UMC server.

Parameters:

request (Request) – A UMC request.

Returns:

The UMC response.

Return type:

Response

Raises:
  • ConnectionError – if the request cannot be send.
  • HTTPError – if an UMC error occurs.
_handle_cookies(response)[source]

Parse cookies from HTTP response and store for next request.

Parameters:httplib.HTTPResponse – The HTTP response.
_get_connection()[source]

Creates a new connection to the host.

Returns:A new connection to the stores host.
Return type:HTTPSConnection
_Client__build_data(data, flavor=None)

Create a dictionary as expected by the UMC Server.

Parameters:
  • data (dict) – The argument for the UMC command.
  • flavor (str) – Optional name of the UMC module flavor, e.g. users/user for UDM modules.
Returns:

A dictionary suitable for sending to the UMC server.

Return type:

dict

_Client__request(request)

Perform a request to the UMC server and return its response.

Parameters:request (Request) – The UMC request.
Returns:The HTTP response.
Return type:httplib.HTTPResponse

univention.lib.umc_module module

Univention common Python library with helper functions for MIME type handling.

univention.lib.umc_module.get_mime_type(data)[source]

Guess MIME type of data.

Parameters:data (bytes) – Some data.
Returns:The MIME type string.
Return type:str
univention.lib.umc_module.get_mime_description(data)[source]

Guess type of data silimar to file.

Parameters:data (bytes) – Some data.
Returns:A descriptive string.
Return type:str
univention.lib.umc_module.compression_mime_type_of_buffer(data)[source]

Guess MIME type of compressed data.

Parameters:data (bytes) – Some compressed data.
Returns:A 2-tuple (mime_type, uncompress_function).
Return type:tuple[str, str]
Raises:univention.admin.uexceptions.valueError – if the compression format is not recognized.
univention.lib.umc_module.uncompress_buffer(data)[source]

Return uncompressed data and its MIME type.

Parameters:data (bytes) – Some compressed data.
Returns:A 2-tuple (mime_type, uncompressed_data). On errors mime_type is None and uncompressed_data is data.
Return type:tuple[str, bytes]
univention.lib.umc_module.uncompress_file(filename)[source]

Return uncompressed file content and its MIME type.

Parameters:filename (str) – The name of the file.
Returns:A 2-tuple (mime_type, uncompressed_data). On errors mime_type is None and uncompressed_data is data.
Return type:tuple[str, bytes]
univention.lib.umc_module.image_mime_type_of_buffer(data)[source]

Guess MIME type of image.

Parameters:data (bytes) – Some image data.
Returns:The MIME type string.
Return type:str
Raises:univention.admin.uexceptions.valueError – if the image format is not supported.
univention.lib.umc_module.imagedimensions_of_buffer(data)[source]

Return image dimension of image.

Parameters:data (bytes) – Some image data.
Returns:A 2-tuple (width, height)
Return type:tuple[int, int]
univention.lib.umc_module.imagecategory_of_buffer(data)[source]

Return MIME types and size information for image.

Strparam bytes data:
 Some (compressed) image data.
Returns:a 3-tuple (image_mime_type, compression_mime_type, dimension) where dimension is {width}x{height} or scalable. None if the format is not recognized.
Return type:tuple[str, str, str]
univention.lib.umc_module.default_filename_suffix_for_mime_type(mime_type, compression_mime_type)[source]

Return default file name suffix for image.

Parameters:
  • mime_type (str) – The MIME type of the image.
  • compression_mime_type (str) – The MIME type of the compression.
Returns:

A suffix string or None if the image format is not supported.

Rytpe:

str

univention.lib.urllib2_ssl module

Univention fork of urllib2 supporting verified SSL connections.

Deprecated since version 4.0: This is directly supported by urllib2 since Python 2.7.9

exception univention.lib.urllib2_ssl.CertificateError[source]

Bases: exceptions.ValueError

univention.lib.urllib2_ssl._dnsname_to_pat(dn, max_wildcards=1)[source]
univention.lib.urllib2_ssl.match_hostname(cert, hostname)[source]

Verify that cert (in decoded format as returned by SSLSocket.getpeercert()) matches the hostname. RFC 2818 rules are mostly followed, but IP addresses are not accepted for hostname.

Parameters:
  • cert – The certificate.
  • hostname (str) – the host name.
Returns:

nothing on success.

Raises:

CertificateError – on failure.

class univention.lib.urllib2_ssl.VerifiedHTTPSConnection(host, **kwargs)[source]

Bases: httplib.HTTPSConnection

connect()[source]

Connect to a host on a given (SSL) port.

class univention.lib.urllib2_ssl.VerifiedHTTPSHandler(**kwargs)[source]

Bases: urllib2.HTTPSHandler

Parameters:

Code example:

import urllib
import univention.urllib2_ssl
opener = urllib2.build_opener(
        univention.urllib2_ssl.VerifiedHTTPSHandler(
                key_file='/etc/univention/ssl/%(hostname)s/private.key' % ucr,
                cert_file='/etc/univention/ssl/%(hostname)s/cert.key' % ucr,
                ca_certs_file='/etc/univention/ssl/ucsCA/CAcert.pem',
))
response = opener.open(url, body).read()
https_open(req)[source]
_getVerifiedHTTPSConnectionInstance(host, **kwargs)[source]