コード例 #1
0
def setup_i18n():
	import locale
	locale.setlocale(locale.LC_ALL, "")
	from univention.lib.i18n import Translation
	translation = Translation('univention-system-setup-scripts')
	translation.set_language()
	return translation.translate
コード例 #2
0
def setup_i18n():
    import locale
    locale.setlocale(locale.LC_ALL, locale.getdefaultlocale())
    language = locale.getdefaultlocale()[0]
    from univention.lib.i18n import Translation
    translation = Translation('univention-system-setup-scripts')
    translation.set_language(language)
    return translation.translate
コード例 #3
0
 def __init__(self):
     signals.Provider.__init__(self)
     self.signal_new('success')
     self.signal_new('failure')
     self._username = None
     self._user_dn = None
     self._password = None
     self.__acls = None
     self.__requests = {}
     Translation.__init__(self)
コード例 #4
0
ファイル: __init__.py プロジェクト: B-Rich/smart
	def __init__( self ):
		signals.Provider.__init__( self )
		self.signal_new( 'success' )
		self.signal_new( 'failure' )
		self._username = None
		self._user_dn = None
		self._password = None
		self.__acls = None
		self.__requests = {}
		Translation.__init__( self )
コード例 #5
0
 def __init__(self, domain='univention-management-console'):
     signals.Provider.__init__(self)
     self.signal_new('success')
     self._username = None
     self._user_dn = None
     self._password = None
     self.__auth_type = None
     self.__acls = None
     self.__current_language = None
     self.__requests = {}
     Translation.__init__(self, domain)
コード例 #6
0
	def __init__(self, locale=None):
		i18n = Translation('univention-management-console')
		try:
			i18n.set_language(locale or 'C')
		except (I18N_Error, AttributeError, TypeError):
			i18n.set_language('C')
		self._ = i18n.translate
		self.pam = self.init()
コード例 #7
0
ファイル: session.py プロジェクト: B-Rich/smart
	def __init__( self, username, password ):
		global users_module
		self.__username = username
		self.__password = password
		self.__user_dn = None
		signals.Provider.__init__( self )
		self.core_i18n = Translation( 'univention-management-console' )
		self.i18n = I18N_Manager()
		self.i18n[ 'umc-core' ] = I18N()

		# stores the module processes [ modulename ] = <>
		self.__processes = {}

		self.__killtimer = {}

		lo = ldap.open( ucr[ 'ldap/server/name' ], int( ucr.get( 'ldap/server/port', 7389 ) ) )

		try:
			# get LDAP connection with machine account
			self.lo, self.po = udm_uldap.getMachineConnection( ldap_master = False )

			# get the LDAP DN of the authorized user
			ldap_dn = self.lo.searchDn( '(&(uid=%s)(objectClass=posixAccount))' % self.__username )
			if ldap_dn:
				self.__user_dn = ldap_dn[ 0 ]
				CORE.info( 'The LDAP DN for user %s is %s' % ( self.__username, self.__user_dn ) )
			else:
				CORE.info( 'The LDAP DN for user %s could not be found' % self.__username )

			# initiate the users/user UDM module
			udm_modules.update()
			users_module = udm_modules.get('users/user')
			udm_modules.init(self.lo, self.po, users_module)
		except ( ldap.LDAPError, IOError ) as e:
			# problems connection to LDAP server or the server is not joined (machine.secret is missing)
			CORE.warn('An error occurred connecting to the LDAP server: %s' % e)
			self.lo = None
			users_module = None
		except udm_errors.base as e:
			# UDM error, user module coule not be initiated
			CORE.warn('An error occurred intializing the UDM users/user module: %s' % e)
			users_module = None

		# read the ACLs
		self.acls = LDAP_ACLs( self.lo, self.__username, ucr[ 'ldap/base' ] )
		self.__command_list = moduleManager.permitted_commands( ucr[ 'hostname' ], self.acls )

		self.signal_new( 'response' )
コード例 #8
0
ファイル: azure_auth.py プロジェクト: Rabie-Zamane/office365
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend
import OpenSSL.crypto
import jwt
from requests.exceptions import RequestException
import subprocess
import shutil

from univention.lib.i18n import Translation
from univention.office365.logging2udebug import get_logger
from univention.office365.udm_helper import UDMHelper
from univention.config_registry.frontend import ucr_update
from univention.config_registry import ConfigRegistry, handler_set, handler_unset


_ = Translation('univention-office365').translate

NAME = "office365"
SCOPE = ["Directory.ReadWrite.All"]  # https://msdn.microsoft.com/Library/Azure/Ad/Graph/howto/azure-ad-graph-api-permission-scopes#DirectoryRWDetail
DEBUG_FORMAT = '%(asctime)s %(levelname)-8s %(module)s.%(funcName)s:%(lineno)d  %(message)s'
LOG_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
SAML_SETUP_SCRIPT_CERT_PATH = "/etc/simplesamlphp/ucs-sso.{domainname}-idp-certificate{adconnection_alias}.crt"
SAML_SETUP_SCRIPT_PATH = "/var/lib/univention-office365/saml_setup{adconnection_alias}.bat"
ADCONNECTION_CONF_BASEPATH = "/etc/univention-office365"

oauth2_auth_url = "https://login.microsoftonline.com/{adconnection}/oauth2/authorize?{params}"
oauth2_token_url = "https://login.microsoftonline.com/{adconnection_id}/oauth2/token"
oauth2_token_issuer = "https://sts.windows.net/{adconnection_id}/"
federation_metadata_url = "https://login.microsoftonline.com/{adconnection_id}/federationmetadata/2007-06/federationmetadata.xml"
resource_url = "https://graph.windows.net"
コード例 #9
0
    MODULE.warn('Ignoring import error: %s' % e)

from univention.management.console.modules.setup import network
from univention.management.console.modules.setup import util
from univention.management.console.modules.setup.checks.ldap import check_if_uid_is_available
from univention.management.console.modules.setup.checks.repositories import get_unreachable_repository_servers
from univention.management.console.modules.setup.checks.univention_join import (
    receive_domaincontroller_master_information,
    set_role_and_check_if_join_will_work,
    check_for_school_domain,
)

ucr = univention.config_registry.ConfigRegistry()
ucr.load()

_translation = Translation('univention-management-console-module-setup')
_ = _translation.translate

i18nXKeyboard = Translation('xkeyboard-config')

RE_IPV4 = re.compile(r'^interfaces/(([^/]+?)(_[0-9])?)/(address|netmask)$')
RE_IPV6_DEFAULT = re.compile(
    r'^interfaces/([^/]+)/ipv6/default/(prefix|address)$')
RE_SPACE = re.compile(r'\s+')
RE_SSL = re.compile(r'^ssl/.*')


class RequestTimeout(UMC_Error):
    msg = _('Request Timeout')
    status = 408
コード例 #10
0
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from univention.lib.i18n import Translation

from univention.management.console.log import MODULE
from univention.management.console.protocol.definitions import MODULE_ERR_COMMAND_FAILED

# for urlparse extensions
from univention.uvmm import helpers
import urlparse

from notifier import Callback

_ = Translation('univention-management-console-modules-uvmm').translate


class Nodes(object):
    """Handler for all commands regarding nodes"""
    def _node_thread_finished(self, thread, result, request, parent):
        """This method is invoked when a threaded request for the
		navigation is finished. The result is send back to the
		client. If the result is an instance of BaseException an error
		is returned."""
        if self._check_thread_error(thread, result, request):
            return

    def node_query(self, request):
        """Searches nodes by the given pattern
コード例 #11
0
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from univention.management.console.log import MODULE
from univention.management.console.config import ucr
from univention.management.console.base import Base

from univention.lib.i18n import Translation

_ = Translation('PACKAGENAME').translate


class Instance(Base):
    pass
コード例 #12
0
ファイル: session.py プロジェクト: B-Rich/smart
class Processor( signals.Provider ):
	"""Implements a proxy and command handler. It handles all internal
	UMCP commands and passes the commands for a module to the
	subprocess.

	:param str username: name of the user who authenticated for this session
	:param str password: password of the user
	"""

	def __init__( self, username, password ):
		global users_module
		self.__username = username
		self.__password = password
		self.__user_dn = None
		signals.Provider.__init__( self )
		self.core_i18n = Translation( 'univention-management-console' )
		self.i18n = I18N_Manager()
		self.i18n[ 'umc-core' ] = I18N()

		# stores the module processes [ modulename ] = <>
		self.__processes = {}

		self.__killtimer = {}

		lo = ldap.open( ucr[ 'ldap/server/name' ], int( ucr.get( 'ldap/server/port', 7389 ) ) )

		try:
			# get LDAP connection with machine account
			self.lo, self.po = udm_uldap.getMachineConnection( ldap_master = False )

			# get the LDAP DN of the authorized user
			ldap_dn = self.lo.searchDn( '(&(uid=%s)(objectClass=posixAccount))' % self.__username )
			if ldap_dn:
				self.__user_dn = ldap_dn[ 0 ]
				CORE.info( 'The LDAP DN for user %s is %s' % ( self.__username, self.__user_dn ) )
			else:
				CORE.info( 'The LDAP DN for user %s could not be found' % self.__username )

			# initiate the users/user UDM module
			udm_modules.update()
			users_module = udm_modules.get('users/user')
			udm_modules.init(self.lo, self.po, users_module)
		except ( ldap.LDAPError, IOError ) as e:
			# problems connection to LDAP server or the server is not joined (machine.secret is missing)
			CORE.warn('An error occurred connecting to the LDAP server: %s' % e)
			self.lo = None
			users_module = None
		except udm_errors.base as e:
			# UDM error, user module coule not be initiated
			CORE.warn('An error occurred intializing the UDM users/user module: %s' % e)
			users_module = None

		# read the ACLs
		self.acls = LDAP_ACLs( self.lo, self.__username, ucr[ 'ldap/base' ] )
		self.__command_list = moduleManager.permitted_commands( ucr[ 'hostname' ], self.acls )

		self.signal_new( 'response' )

	def shutdown( self ):
		"""Instructs the module process to shutdown"""
		CORE.info( 'The session is shutting down. Sending UMC modules an EXIT request (%d processes)' % len( self.__processes ) )
		for module_name in self.__processes:
			CORE.info( 'Ask module %s to shutdown gracefully' % module_name )
			req = Request( 'EXIT', arguments = [ module_name, 'internal' ] )
			self.__processes[ module_name ].request( req )

	def __del__( self ):
		CORE.process( 'Processor: dying' )
		for process in self.__processes.values():
			del process

	def get_module_name( self, command ):
		"""Returns the name of the module that provides the given command

		:param str command: the command name
		"""
		return moduleManager.module_providing( self.__comand_list, command )

	def request( self, msg ):
		"""Handles an incoming UMCP request and passes the requests to
		specific handler functions.

		:param Request msg: UMCP request
		"""
		if msg.command == 'EXIT':
			self.handle_request_exit( msg )
		elif msg.command == 'GET':
			self.handle_request_get( msg )
		elif msg.command == 'SET':
			self.handle_request_set( msg )
		elif msg.command == 'VERSION':
			self.handle_request_version( msg )
		elif msg.command == 'COMMAND':
			self.handle_request_command( msg )
		elif msg.command == 'UPLOAD':
			self.handle_request_upload( msg )
		elif msg.command in ( 'STATUS', 'CANCEL', 'CLOSE' ):
			self.handle_request_unknown( msg )
		else:
			self.handle_request_unknown( msg )

	def _purge_child(self, module_name):
		if module_name in self.__processes:
			CORE.process( 'module %s is still running - purging module out of memory' % module_name)
			pid = self.__processes[ module_name ].pid()
			os.kill(pid, 9)
		return False

	def handle_request_exit( self, msg ):
		"""Handles an EXIT request. If the request does not have an
		argument that contains a valid name of a running UMC module
		instance the request is returned as a bad request.

		If the request is valid it is passed on to the module
		process. Additionally a timer of 3000 milliseconds is
		started. After that amount of time the module process MUST have
		been exited itself. If not the UMC server will kill the module
		process.

		:param Request msg: UMCP request
		"""
		if len( msg.arguments ) < 1:
			return self.handle_request_unknown( msg )

		module_name = msg.arguments[ 0 ]
		if module_name:
			if module_name in self.__processes:
				self.__processes[ module_name ].request( msg )
				CORE.info( 'Ask module %s to shutdown gracefully' % module_name )
				# added timer to kill away module after 3000ms
				cb = notifier.Callback( self._purge_child, module_name )
				self.__killtimer[ module_name ] = notifier.timer_add( 3000, cb )
			else:
				CORE.info( 'Got EXIT request for a non-existing module %s' % module_name )

	def handle_request_version( self, msg ):
		"""Handles a VERSION request by returning the version of the UMC
		server's protocol version.

		:param Request msg: UMCP request
		"""
		res = Response( msg )
		res.status = SUCCESS # Ok
		res.body[ 'version' ] = VERSION

		self.signal_emit( 'response', res )

	def _get_user_obj(self):
		try:
			# make sure that the UDM users/user module could be initiated
			if not users_module:
				raise udm_errors.base('UDM module users/user could not be initiated')

			# open an LDAP connection with the user password and credentials
			lo = udm_uldap.access(host = ucr.get('ldap/server/name'), base = ucr.get('ldap/base'), port = int(ucr.get('ldap/server/port', '7389')), binddn = self.__user_dn, bindpw = self.__password, follow_referral=True)

			# try to open the user object
			userObj = udm_objects.get(users_module, None, lo, self.po, self.__user_dn)
			if not userObj:
				raise udm_errors.noObject()
			userObj.open()
			return userObj
		except udm_errors.noObject as e:
			CORE.warn('Failed to open UDM user object for user %s' % (self.__username))
		except (udm_errors.base, ldap.LDAPError) as e:
			CORE.warn('Failed to open UDM user object %s: %s' % (self.__user_dn, e))
		return None

	def handle_request_get( self, msg ):
		"""Handles a GET request. The following possible variants are supported:

		modules/list
			Returns a list of all available UMC modules within the current session

		categories/list
			Returns a list of all known categories

		user/preferences
			Returns the user preferences as a dict.

		:param Request msg: UMCP request
		"""

		res = Response( msg )

		if 'modules/list' in msg.arguments:
			modules = []
			for id, module in self.__command_list.items():
				# check for translation
				if module.flavors:
					for flavor in module.flavors:
						translationId = flavor.translationId
						if not translationId:
							translationId = id
						modules.append( { 'id' : id, 'flavor' : flavor.id, 'name' : self.i18n._( flavor.name, translationId ), 'description' : self.i18n._( flavor.description, translationId ), 'icon' : flavor.icon, 'categories' : module.categories, 'priority' : flavor.priority } )
				else:
						modules.append( { 'id' : id, 'name' : self.i18n._( module.name, id ), 'description' : self.i18n._( module.description, id ), 'icon' : module.icon, 'categories' : module.categories, 'priority' : module.priority } )
			res.body[ 'modules' ] = modules
			_ucr_dict = dict( ucr.items() )

			categories = []
			for catID, category in categoryManager.items():
				categories.append( { 'id' : catID, 'name' : self.i18n._( category.name, category.domain ).format( **_ucr_dict ), 'priority' : category.priority } )

			res.body[ 'categories' ] = categories
			CORE.info( 'Modules: %s' % modules )
			CORE.info( 'Categories: %s' % str( res.body[ 'categories' ] ) )
			res.status = SUCCESS # Ok

		elif 'categories/list' in msg.arguments:
			res.body[ 'categories' ] = categoryManager.all()
			res.status = SUCCESS # Ok
		elif 'user/preferences' in msg.arguments:
			# fallback is an empty dict
			res.body['preferences'] = {}

			# query user's UMC properties
			userObj = self._get_user_obj()
			if userObj:
				res.body['preferences'] = dict(userObj.info.get('umcProperty', []))
				res.status = SUCCESS
			else:
				res.status = BAD_REQUEST_INVALID_OPTS
		else:
			res.status = BAD_REQUEST_INVALID_ARGS

		self.signal_emit( 'response', res )

	def handle_request_set( self, msg ):
		"""Handles a SET request. No argument may be given. The
		variables that should be set are passed via the request
		options. Currently the only variable that may be set is the
		locale. If any unknown variable is given the the request is
		invalidated.

		:param Request msg: UMCP request
		"""
		res = Response( msg )
		if len( msg.arguments ):
			res.status = BAD_REQUEST_INVALID_ARGS
			res.message = status_description( res.status )

			self.signal_emit( 'response', res )
			return

		res.status = SUCCESS
		if not isinstance(msg.options, dict):
			raise InvalidOptionsError
		for key, value in msg.options.items():
			if key == 'locale':
				try:
					self.core_i18n.set_language( value )
					CORE.info( 'Setting locale: %s' % value )
					self.i18n.set_locale( value )
				except I18N_Error, e:
					res.status = BAD_REQUEST_UNAVAILABLE_LOCALE
					res.message = status_description( res.status )
					CORE.warn( 'Setting locale to specified locale failed (%s)' % value )
					CORE.warn( 'Falling back to C' )
					self.core_i18n.set_language( 'C' )
					self.i18n.set_locale( 'C' )
					break
			elif key == 'user' and isinstance(value, dict) and 'preferences' in value:
				# try to open the user object
				userObj = self._get_user_obj()
				if not userObj:
					res.status = BAD_REQUEST_INVALID_OPTS
					res.message = status_description( res.status )
					break
				try:
					# make sure we got a dict
					prefs = value['preferences']
					if not isinstance(prefs, dict):
						raise ValueError('user preferences are not a dict: %s' % prefs)

					# iterate over all given user preferences
					newPrefs = []
					for prefKey, prefValue in prefs.iteritems():
						if not isinstance(prefKey, basestring):
							raise ValueError('user preferences keys needs to be strings: %s' % prefKey)

						# we can put strings directly into the dict
						if isinstance(prefValue, basestring):
							newPrefs.append((prefKey, prefValue))
						else:
							newPrefs.append((prefKey, json.dumps(prefValue)))

					if newPrefs:
						# eliminate double entries
						newPrefs = dict(userObj.info.get('umcProperty', []) + newPrefs)

						# apply changes
						userObj.info['umcProperty'] = newPrefs.items()
						userObj.modify()

				except (ValueError, udm_errors.base) as e:
					CORE.warn('Could not set given option: %s' % e)
					res.status = BAD_REQUEST_INVALID_OPTS
					res.message = status_description( res.status )
					break
			else:
コード例 #13
0
# user. The token is then deleted from the database.                        #
#
#

import os.path
import smtplib
import urllib
from email.mime.nonmultipart import MIMENonMultipart
from email.utils import formatdate
import email.charset

from univention.config_registry import ConfigRegistry
from univention.lib.i18n import Translation
from univention.management.console.modules.passwordreset.send_plugin import UniventionSelfServiceTokenEmitter

_ = Translation('univention-self-service-passwordreset-umc').translate


class SendEmail(UniventionSelfServiceTokenEmitter):
    def __init__(self, *args, **kwargs):
        super(SendEmail, self).__init__(*args, **kwargs)
        self.server = self.ucr.get(
            "umc/self-service/passwordreset/email/server", "localhost")

    @staticmethod
    def send_method():
        return "email"

    @staticmethod
    def send_method_label():
        return _("Email")
コード例 #14
0
import tempfile
from locale import getlocale

from six.moves.configparser import RawConfigParser, ParsingError
from six.moves import urllib_request, http_client
from six.moves.urllib_parse import urlencode

from univention.lib.i18n import Translation
from univention.config_registry.misc import key_shell_escape
from univention.config_registry import interfaces
from univention.appcenter.log import get_base_logger
from univention.appcenter.ucr import ucr_get, ucr_keys

# "global" translation for univention-appcenter
# also provides translation for univention-appcenter-docker etc
_ = Translation('univention-appcenter').translate


utils_logger = get_base_logger().getChild('utils')


def read_ini_file(filename, parser_class=RawConfigParser):
	parser = parser_class()
	try:
		with open(filename, 'rb') as f:
			parser.readfp(f)
	except TypeError:
		pass
	except EnvironmentError:
		pass
	except ParsingError as exc:
コード例 #15
0
ファイル: __init__.py プロジェクト: spaceone/ucs-school
from univention.uldap import explodeDn

from ucsschool.lib.schoolldap import LDAP_Connection, SchoolBaseModule, Display, SchoolSanitizer
from ucsschool.lib.schoollessons import SchoolLessons
from ucsschool.lib.smbstatus import SMB_Status
import ucsschool.lib.internetrules as internetrules
from ucsschool.lib.models import School, ComputerRoom, User

# import univention.management.console.modules.schoolexam.util as exam_util

from .italc2 import ITALC_Manager, ITALC_Error

from notifier.nf_qt import _exit

_ = Translation('ucs-school-umc-computerroom').translate

ROOMDIR = '/var/cache/ucs-school-umc-computerroom'
FN_SCREENSHOT_DENIED = _(
    '/usr/share/ucs-school-umc-computerroom/screenshot_denied.jpg')
FN_SCREENSHOT_NOTREADY = _(
    '/usr/share/ucs-school-umc-computerroom/screenshot_notready.jpg')


def compare_dn(a, b):
    return a and b and a.lower() == b.lower()


def _getRoomFile(roomDN):
    if roomDN.startswith('cn='):
        dnParts = explodeDn(roomDN, True)
コード例 #16
0
import subprocess
from contextlib import contextmanager
import threading
from logging import getLogger, DEBUG, Handler
from time import sleep

import apt_pkg
import apt
import apt.progress
from apt.cache import FetchFailedException, LockFailedException, ProblemResolver

apt_pkg.init()

from univention.lib.locking import get_lock, release_lock
from univention.lib.i18n import Translation
_ = Translation('univention-lib').translate

# FIXME: Requires univention-updater (but this requires univention-lib...)
# FIXME: The path to the script is hardcoded everywhere it is used.
# TODO: Solution: Put all the logic in univention-lib
CMD_DISABLE_EXEC = '/usr/share/univention-updater/disable-apache2-umc'
CMD_ENABLE_EXEC = [
    '/usr/share/univention-updater/enable-apache2-umc', '--no-restart'
]


class LockError(Exception):
    """
	Lock error for the package manager.
	Not to be confused with :py:class:`LockFailedException`
	"""
コード例 #17
0
from univention.lib.package_manager import PackageManager
from univention.lib.umc import Client, ConnectionError, HTTPError, Forbidden
from univention.admin.uexceptions import noObject
from univention.management.console.base import Base, UMC_Error
from univention.management.console.log import MODULE
from univention.management.console.config import ucr
from univention.management.console.ldap import get_machine_connection
from univention.management.console.modules.decorators import simple_response, sanitize
from univention.management.console.modules.sanitizers import StringSanitizer, ChoicesSanitizer

from ucsschool.lib.models import School, SchoolDCSlave

from univention.lib.i18n import Translation

_ = Translation('ucs-school-umc-installer').translate
os.umask(0o022)  # switch back to default umask

RE_FQDN = re.compile('^[a-z]([a-z0-9-]*[a-z0-9])*\.([a-z0-9]([a-z0-9-]*[a-z0-9])*[.])*[a-z0-9]([a-z0-9-]*[a-z0-9])*$')
RE_HOSTNAME = re.compile('^[a-z]([a-z0-9-]*[a-z0-9])*(\.([a-z0-9]([a-z0-9-]*[a-z0-9])*[.])*[a-z0-9]([a-z0-9-]*[a-z0-9])*)?$')  # keep in sync with schoolinstaller.js widgets.master.regExp
RE_HOSTNAME_OR_EMPTY = re.compile('^([a-z]([a-z0-9-]*[a-z0-9])*(\.([a-z0-9]([a-z0-9-]*[a-z0-9])*[.])*[a-z0-9]([a-z0-9-]*[a-z0-9])*)?)?$')
RE_OU = re.compile('^[a-zA-Z0-9](([a-zA-Z0-9_]*)([a-zA-Z0-9]$))?$')
RE_OU_OR_EMPTY = re.compile('^([a-zA-Z0-9](([a-zA-Z0-9_]*)([a-zA-Z0-9]$))?)?$')

CMD_ENABLE_EXEC = ['/usr/share/univention-updater/enable-apache2-umc', '--no-restart']
CMD_DISABLE_EXEC = '/usr/share/univention-updater/disable-apache2-umc'

CERTIFICATE_PATH = '/etc/univention/ssl/ucsCA/CAcert.pem'

# class SetupSanitizer(StringSanitizer):
#
コード例 #18
0
#!/usr/bin/python2.7
# taken from https://git.knut.univention.de/univention/ucsschool/blob/6022c7d9296c76ea9a3f4a98190972fef2ddf434/ucs-school-umc-helpdesk/umc/python/helpdesk/__init__.py#L70
# bugzilla Bug 29975
# Fixed in UCS@school 4.0 R2

from univention.management.console.log import MODULE
from univention.management.console.config import ucr

from univention.lib.i18n import Translation
from ucsschool.lib import SchoolBaseModule

import notifier
import smtplib

_ = Translation('ucs-school-umc-helpdesk').translate


class Instance(SchoolBaseModule):

	def send(self, request):
		func = notifier.Callback(self._send_thread, '*****@*****.**', ucr['ucsschool/helpdesk/recipient'].split(' '), request.options['username'], request.options['school'], request.options['category'], request.options['message'])
		MODULE.info('sending mail: starting thread')
		thread = notifier.threads.Simple('HelpdeskMessage', func)
		thread.run()

	def _send_thread(self, sender, recipients, username, school, category, message):
		MODULE.info('sending mail: thread running')

		msg = u'From: ' + sender + u'\r\n'
		msg += u'To: ' + (', '.join(recipients)) + u'\r\n'
		msg += u'Subject: %s (%s: %s)\r\n' % (category, _('School'), school)
コード例 #19
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.
import sys
import re
from datetime import datetime

# translation: manually set_language() because
# for some reason, the default locale is not used by default
import locale
from univention.lib.i18n import Translation
translation = Translation('univention-system-setup-scripts')
default_locale = locale.getdefaultlocale()
translation.set_language(default_locale[0])
_ = translation.translate
locale.setlocale(locale.LC_ALL,
                 default_locale)  # needed for external translation (e.g. apt)

import univention.config_registry
from util import PATH_SETUP_SCRIPTS, PATH_PROFILE
ucr = univention.config_registry.ConfigRegistry()


class SetupScript(object):
    '''Baseclass for all Python-based Setup-Scripts.

	Script lifecycle:
コード例 #20
0
# <http://www.gnu.org/licenses/>.

from ldap.filter import filter_format
from univention.lib.i18n import Translation

from univention.management.console.modules import UMC_Error
from univention.management.console.modules.decorators import sanitize
from univention.management.console.modules.sanitizers import ListSanitizer, DictSanitizer, StringSanitizer
from univention.management.console.log import MODULE

import univention.admin.uexceptions as udm_exceptions

from ucsschool.lib.schoolldap import LDAP_Connection, SchoolBaseModule, Display, USER_READ, USER_WRITE, MACHINE_WRITE, SchoolSanitizer
from ucsschool.lib.models import User, Teacher, TeachersAndStaff, SchoolClass, WorkGroup

_ = Translation('ucs-school-umc-groups').translate


def only_workgroup_admin(func):
    def _decorated(self, request, *args, **kwargs):
        if request.flavor != 'workgroup-admin':
            raise UMC_Error('not supported')
        return func(self, request, *args, **kwargs)

    return _decorated


def get_group_class(request):
    if request.flavor in ('workgroup', 'workgroup-admin'):
        return WorkGroup
    elif request.flavor == 'teacher':
コード例 #21
0
Mixins for UMC module classes
=============================

This module provides some mixins that can be incorporated in existing UMC
modules. These mixins extend the functionality of the module in an easy-to-use
way. Just let your module derive from
:class:`~univention.management.console.module.Base` (as before) and the mixin
classes.
"""
import random

from univention.lib.i18n import Translation
from univention.management.console.error import BadRequest
from univention.management.console.modules.decorators import simple_response

_ = Translation('univention-management-console').translate


class Progress(object):

	"""
	Class to keep track of the progress during execution of a function.
	Used internally.
	"""

	def __init__(self, progress_id, title, total):
		self.id = progress_id
		self.title = title
		self.message = ''
		self.current = 0.0
		self.total = total
コード例 #22
0
import mimetypes
import time
import re
import copy

try:
    import simplejson as json
except:
    import json

from .definitions import *
from ..log import PARSER, PROTOCOL

from univention.lib.i18n import Translation

_ = Translation('univention.management.console').translate


# Exceptions
class ParseError(Exception):
    pass


class IncompleteMessageError(Exception):
    pass


class UnknownCommandError(Exception):
    pass

コード例 #23
0
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <https://www.gnu.org/licenses/>.

import time
import psutil

from univention.lib.i18n import Translation
from univention.management.console.modules import Base, UMC_Error
from univention.management.console.log import MODULE

from univention.management.console.modules.decorators import sanitize, simple_response
from univention.management.console.modules.sanitizers import PatternSanitizer, ChoicesSanitizer, ListSanitizer, IntegerSanitizer

_ = Translation('univention-management-console-module-top').translate


class Instance(Base):

	@sanitize(
		pattern=PatternSanitizer(default='.*'),
		category=ChoicesSanitizer(choices=['user', 'pid', 'command', 'all'], default='all')
	)
	@simple_response
	def query(self, pattern, category='all'):
		processes = []
		for process in psutil.process_iter():
			try:
				cpu_time = process.cpu_times()
				proc = {
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from univention.management.console.config import ucr
from univention.management.console.modules.diagnostic import Warning, ProblemFixed

from univention.admin.uldap import getAdminConnection

from univention.lib.i18n import Translation
_ = Translation('univention-management-console-module-diagnostic').translate

title = _('Server Role Windows')
description = '\n'.join([
    _('Several services rely on the attribute "univentionServerRole" to search and identify objects in OpenLDAP.'
      ),
    _('Objects that implicitly satisfy the criteria of a Univention Object but lack this attribute should be migrated.'
      ),
])

_WINDOWS_SERVER_ROLES = {
    'computers/windows_domaincontroller': 'windows_domaincontroller',
    'computers/windows': 'windows_client',
}

コード例 #25
0
#

# this is just a "one-shot", non-packaged script
# that generates the DiaryEvent objects on a live UCS Master
# python $0 2> errors >> /usr/lib/python2.7/dist-packages/univention/admindiary/events.py

from __future__ import print_function
import sys

from univention.lib.i18n import Translation
from univention.udm import UDM
from univention.udm.helpers import get_all_udm_module_names

udm = UDM.admin().version(2)

translation = Translation(None)


def modules():
	for m in get_all_udm_module_names():
		yield udm.get(m)._orig_udm_module


def print_events(m):
	name = m.module
	icon = 'domain'
	if name.startswith('users/'):
		icon = 'users'
	if name.startswith('groups/'):
		icon = 'users'
	if name.startswith('computers/'):
コード例 #26
0
ファイル: setup_script.py プロジェクト: B-Rich/smart
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.
import sys
import re
from datetime import datetime

# translation: manually set_language() because
# for some reason, the default locale is not used by default
import locale
from univention.lib.i18n import Translation
translation = Translation('univention-system-setup-scripts')
default_locale = locale.getdefaultlocale()
translation.set_language(default_locale[0])
_ = translation.translate
locale.setlocale(locale.LC_ALL, default_locale) # needed for external translation (e.g. apt)

import univention.config_registry
from util import PATH_SETUP_SCRIPTS, PATH_PROFILE
ucr = univention.config_registry.ConfigRegistry()

class SetupScript(object):
	'''Baseclass for all Python-based Setup-Scripts.

	Script lifecycle:
	  __init__() -> up()
	  run() -> (inner_run() -> commit_ucr()) -> down()
コード例 #27
0
import re
import subprocess
import lxml.html

from univention.lib.i18n import Translation

import univention.admin.uldap

from univention.management.console.base import Base
from univention.management.console.log import MODULE
from univention.management.console.config import ucr
from univention.management.console.modules import UMC_Error
from univention.management.console.modules.decorators import simple_response, log, sanitize
from univention.management.console.modules.sanitizers import PatternSanitizer, ChoicesSanitizer

_ = Translation('univention-management-console-module-printers').translate


class Instance(Base):
    def init(self):
        self._hostname = ucr.get('hostname')

    @sanitize(pattern=PatternSanitizer(default='.*'),
              key=ChoicesSanitizer(
                  choices=['printer', 'description', 'location'],
                  required=True))
    @simple_response
    def list_printers(self, key, pattern):
        """ Lists the printers for the overview grid. """

        quota = self._quota_enabled()  # we need it later
コード例 #28
0
#!/usr/bin/python
# taken from https://git.knut.univention.de/univention/ucsschool/blob/842f439e29d8415ff5b9bd5f293ef3a5c980f660/ucs-school-umc-printermoderation/umc/python/printermoderation/__init__.py#L151
# bugzilla Bug 38270
# Fixed in UCS@school 4.0 R2

import os

from univention.lib.i18n import Translation
from univention.management.console.modules import UMC_Error
from ucsschool.lib import SchoolBaseModule

CUPSPDF_DIR = '/var/spool/cups-pdf/'
CUPSPDF_USERSUBDIR = None

_ = Translation('ucs-school-umc-printermoderation').translate


class Instance(SchoolBaseModule):
    def download(self, request):
        """Download a printjob of a specified user

		requests.options = {}
		'username' -- owner of the print job
		'filename' -- relative filename of the print job

		return: <PDF document>
		"""
        if request.options['username'].find(
                '/') > 0 or request.options['printjob'].find('/') > 0:
            raise UMC_Error('Invalid file')
コード例 #29
0
ファイル: __init__.py プロジェクト: spaceone/ucs-school
 def __init__(self, computerroom, italc):
     self.computerroom = computerroom
     self.italc = italc
     self._ = Translation(self.gettext_domain).translate
コード例 #30
0
ファイル: __init__.py プロジェクト: spaceone/ucs-school
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from univention.management.console.log import MODULE
from univention.management.console.modules import UMC_Error
from univention.management.console.modules.decorators import sanitize
from univention.management.console.modules.sanitizers import StringSanitizer, BooleanSanitizer

import univention.admin.uexceptions as udm_exceptions

from univention.lib.i18n import Translation

from ucsschool.lib.schoolldap import LDAP_Connection, SchoolBaseModule, Display, USER_WRITE, SchoolSanitizer
from ucsschool.lib.models import User

_ = Translation('ucs-school-umc-schoolusers').translate


def get_exception_msg(
        exc):  # TODO: str(exc) would be nicer, Bug #27940, 30089, 30088
    msg = getattr(exc, 'message', '')
    for arg in exc.args:
        if isinstance(arg, unicode):
            arg = arg.encode('utf-8')
        if str(arg) not in msg:
            msg = '%s %s' % (msg, arg)
    return msg


class Instance(SchoolBaseModule):
    @sanitize(
コード例 #31
0
ファイル: util.py プロジェクト: spaceone/ucs-school
from datetime import datetime, date
from ldap.filter import escape_filter_chars
import traceback

from univention.lib.i18n import Translation
from univention.management.console.log import MODULE
from univention.management.console.config import ucr
from univention.admin.filter import conjunction, expression

import univention.admin.uexceptions as uexceptions
from univention.admincli import license_check
import univention.admin.uldap

from ucsschool.lib.models import User, Student, Teacher, Staff, TeachersAndStaff, Attribute

_ = Translation('ucs-school-umc-csv-import').translate


def unformat_date(value, date_format):
    try:
        date_obj = datetime.strptime(value, date_format)
        if '%y' in date_format:
            # date format has only 2 year digits
            # so 01.01.40 -> 2040-01-01 which is not wanted
            if date_obj > datetime.now():
                date_obj = date(date_obj.year - 100, date_obj.month,
                                date_obj.day)
        return date_obj.strftime('%Y-%m-%d')
    except (TypeError, ValueError):
        return value
コード例 #32
0
# <http://www.gnu.org/licenses/>.

import re

import ipaddr

from univention.lib.i18n import Translation
from univention.config_registry import ConfigRegistry
from univention.management.console.log import MODULE

from univention.management.console.modules.setup.util import detect_interfaces

ucr = ConfigRegistry()
ucr.load()

_translation = Translation('univention-management-console-module-setup')
_ = _translation.translate

RE_INTERFACE = re.compile(
    r'^interfaces/(?!(?:primary|restart/auto|handler)$)([^/]+?)(_[0-9]+)?/')
RE_IPV6_ID = re.compile(r'^[a-zA-Z0-9]+\Z')
# VALID_NAME_RE = re.compile(r'^(?![.]{1,2}\Z)[^/ \t\n\r\f]{1,15}\Z')

PHYSICAL_INTERFACES = [dev['name'] for dev in detect_interfaces()]


class DeviceError(ValueError):
    def __init__(self, msg, device=None):
        if device is not None:
            msg = '%s: %s' % (device, msg)
        self.device = device
コード例 #33
0
import sys
import copy
import codecs
import tempfile
import subprocess

from univention.directory.reports.error import ReportError
from univention.directory.reports.parser import Parser
from univention.directory.reports.output import Output
from univention.directory.reports.interpreter import Interpreter
from univention.directory.reports import admin

import trml2pdf

from univention.lib.i18n import Translation
_ = Translation('univention-directory-reports').translate


class Document(object):
    (TYPE_LATEX, TYPE_CSV, TYPE_RML, TYPE_UNKNOWN) = range(4)

    @classmethod
    def get_type(cls, template):
        if template.endswith('.tex'):
            return cls.TYPE_LATEX
        elif template.endswith('.csv'):
            return cls.TYPE_CSV
        elif template.endswith('.rml'):
            return cls.TYPE_RML
        return cls.TYPE_UNKNOWN
コード例 #34
0
import univention.hooks
import notifier.threads

from univention.lib.i18n import Translation
from univention.lib import atjobs
from univention.management.console.log import MODULE
from univention.management.console.config import ucr
from univention.management.console.modules import Base
from univention.management.console.modules.decorators import simple_response, sanitize
from univention.management.console.modules.sanitizers import ChoicesSanitizer, StringSanitizer, IntegerSanitizer

from univention.updater.tools import UniventionUpdater
from univention.updater.errors import RequiredComponentError

_ = Translation('univention-management-console-module-updater').translate

# the file whose file time is used as the 'serial' value for the 'Components' grid.
COMPONENTS_SERIAL_FILE = '/etc/apt/sources.list.d/20_ucs-online-component.list'

# serial files for the 'Updates' page. Whenever only one of these
# files have changed we have to refresh all elements of the
# 'Updates' page.
UPDATE_SERIAL_FILES = [
    '/etc/apt/mirror.list',
    '/etc/apt/sources.list.d/15_ucs-online-version.list',
    '/etc/apt/sources.list.d/18_ucs-online-errata.list',
    '/etc/apt/sources.list.d/20_ucs-online-component.list'
]

HOOK_DIRECTORY = '/usr/share/pyshared/univention/management/console/modules/updater/hooks'