示例#1
0
def showLogs(logLevel=7, color=True):
    """
    A contextmanager that returns a usable logger that is configured
    to log debug output.
    """
    from OPSI.Logger import Logger

    logger = Logger()

    logLevelBefore = logger.getConsoleLevel()

    # We might want to have a better log format:
    # logger.setLogFormat(u'[%l] [%D] %M (%F|%N)')

    try:
        logger.setConsoleLevel(logLevel)
        logger.setConsoleColor(color)
        yield logger
    finally:
        logger.setConsoleLevel(logLevelBefore)
示例#2
0
:copyright: uib GmbH <*****@*****.**>
:author: Jan Schneider <*****@*****.**>
:author: Niko Wenselowski <*****@*****.**>
:license: GNU Affero General Public License version 3
"""

import time
import threading

from OPSI.Exceptions import OpsiAuthenticationError
from OPSI.Types import forceInt, forceUnicode
from OPSI.Logger import Logger
from OPSI.Util import randomString

logger = Logger()


class Session(object):
    def __init__(self,
                 sessionHandler,
                 name=u'OPSISID',
                 sessionMaxInactiveInterval=120):
        self.sessionHandler = sessionHandler
        self.name = forceUnicode(name)
        self.sessionMaxInactiveInterval = forceInt(sessionMaxInactiveInterval)
        self.created = time.time()
        self.lastModified = time.time()
        self.sessionTimer = None
        self.uid = randomString(32)
        self.ip = u''
示例#3
0
		"25": u"Multi-system chassis",
		"26": u"Compact PCI",
		"27": u"Advanced TCA",
		"28": u"Blade",
		"29": u"Blade Enclosure",
		"30": u"Tablet",
		"31": u"Convertible",
		"32": u"Detachable",
		"33": u"IoT Gateway",
		"34": u"Embedded PC",
		"35": u"Mini PC",
		"36": u"Stick PC"
	}
}

logger = Logger()


def getHardwareInformationFromWMI(conf):
	wmiObj = wmi.WMI()

	opsiValues = {}

	for oneClass in conf:
		if not oneClass.get('Class') or not oneClass['Class'].get('Opsi') or not oneClass['Class'].get('WMI'):
			continue

		opsiName = oneClass['Class']['Opsi']
		wmiQuery = oneClass['Class']['WMI']
		mapClass = ''
示例#4
0
import re
from collections import namedtuple

from OPSI.Config import (FILE_ADMIN_GROUP as _FILE_ADMIN_GROUP,
                         OPSI_ADMIN_GROUP as _ADMIN_GROUP, DEFAULT_DEPOT_USER
                         as _CLIENT_USER, OPSICONFD_USER as _OPSICONFD_USER)
from OPSI.Exceptions import BackendConfigurationError, BackendMissingDataError
from OPSI.Logger import LOG_DEBUG, Logger
from OPSI.Util import findFiles
from OPSI.System.Posix import (getLocalFqdn as getLocalFQDN, isCentOS,
                               isDebian, isOpenSUSE, isRHEL, isSLES, isUbuntu,
                               isUCS)

__all__ = ('setRights', 'setPasswdRights')

LOGGER = Logger()

_POSSIBLE_DEPOT_DIRECTORIES = (u'/var/lib/opsi/depot/', u'/opt/pcbin/install/')
_CACHED_DEPOT_DIRECTORY = None
_CACHED_WORKBENCH_DIRECTORY = None
_HAS_ROOT_RIGHTS = os.geteuid() == 0

KNOWN_EXECUTABLES = frozenset((
    u'create_driver_links.py',
    u'opsi-deploy-client-agent',
    u'service_setup.sh',
    u'setup.py',
    u'show_drivers.py',
    u'winexe',
    u'windows-image-detector.py',
))
示例#5
0
from OPSI.Logger import Logger, LOG_DEBUG
from OPSI.Types import (forceBool, forceFilename, forceFqdn, forceInt,
                        forceIPAddress, forceNetworkAddress, forceUnicode)

__all__ = ('BLOWFISH_IV', 'PickleString', 'RANDOM_DEVICE', 'blowfishDecrypt',
           'blowfishEncrypt', 'chunk', 'compareVersions',
           'decryptWithPrivateKeyFromPEMFile', 'deserialize',
           'encryptWithPublicKeyFromX509CertificatePEMFile', 'findFiles',
           'formatFileSize', 'fromJson', 'generateOpsiHostKey', 'getfqdn',
           'ipAddressInNetwork', 'isRegularExpressionPattern',
           'librsyncDeltaFile', 'librsyncPatchFile', 'librsyncSignature',
           'md5sum', 'objectToBash', 'objectToBeautifiedText', 'objectToHtml',
           'randomString', 'removeDirectory', 'removeUnit',
           'replaceSpecialHTMLCharacters', 'serialize', 'timestamp', 'toJson')

logger = Logger()

if os.name == 'posix':
    from duplicity import librsync
elif os.name == 'nt':
    try:
        import librsync
    except Exception as e:
        logger.error(u"Failed to import librsync: %s" % e)

BLOWFISH_IV = 'OPSI1234'
RANDOM_DEVICE = u'/dev/urandom'
UNIT_REGEX = re.compile(r'^(\d+\.*\d*)\s*(\w{0,4})$')
_ACCEPTED_CHARACTERS = ("abcdefghijklmnopqrstuvwxyz"
                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                        "0123456789")
示例#6
0
import fcntl
import gettext
import gzip
import os
import shutil
import sys
import termios

from OPSI.Exceptions import (
	BackendConfigurationError, OpsiBackupFileError,
	OpsiBackupBackendNotFound, OpsiError)
from OPSI.Logger import Logger, LOG_DEBUG
from OPSI.Types import forceList, forceUnicode
from OPSI.Util.File.Opsi import OpsiBackupArchive

logger = Logger()

try:
	translation = gettext.translation('opsi-utils', '/usr/share/locale')
	_ = translation.ugettext
except Exception as error:
	logger.error(u"Locale not found: {0}", error)

	def _(string):
		""" Function for translating text. """
		return string


WARNING_DIFF = _(u"""WARNING: Your system config is different from the one recorded with this backup.
This means the backup was probably taken for another machine and restoring it might leave this opsi installation unusable.
Do you wish to continue? [y/n]""")
示例#7
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Manual tests for the JSONRPCBackend.

:author: Jan Schneider <*****@*****.**>
:author: Niko Wenselowski <*****@*****.**>
:license: GNU Affero General Public License version 3
"""

import time
import threading
from OPSI.Logger import Logger, LOG_INFO
from OPSI.Backend.JSONRPC import JSONRPCBackend

logger = Logger()


def checkIfMultipleCallsSucceed():
    be = JSONRPCBackend(address='192.168.105.1',
                        username='******',
                        password='******')
    first = be.backend_info()
    second = be.backend_info()
    third = be.backend_info()

    assert first == second
    assert second == third


def checkIfConnectionWithCertWorks():
示例#8
0
@author: Niko Wenselowski <*****@*****.**>
@license: GNU General Public License version 2
"""

import time
import gettext
import locale
import signal as ui_signal
from snack import *

from OPSI.Logger import Logger
from OPSI.Types import (forceBool, forceInt, forceList, forceUnicode,
                        forceUnicodeList)
from OPSI.Util.Message import MessageObserver, ProgressObserver

logger = Logger()
encoding = locale.getpreferredencoding()

try:
    translation = gettext.translation('python-opsi', '/usr/share/locale')
    _ = translation.ugettext
except Exception as e:
    logger.error(u"Locale not found: %s" % e)

    def _(string):
        """
		Fallback function for providing translations.
		"""
        return string

示例#9
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Testing a manual backend conversion.

:author: Jan Schneider <*****@*****.**>
:author: Niko Wenselowski <*****@*****.**>
:license: GNU Affero General Public License version 3
"""

from OPSI.Logger import Logger, LOG_DEBUG
from OPSI.Backend.MySQL import MySQLBackend
from OPSI.Backend.File import FileBackend
from OPSI.Backend.Backend import ExtendedConfigDataBackend

logger = Logger()


def main():
    # TODO: make this a test that is run automatically
    #init and reset
    fileBackend = ExtendedConfigDataBackend(FileBackend())
    fileBackend.backend_deleteBase()
    fileBackend.backend_createBase()

    mysqlBackend = ExtendedConfigDataBackend(
        MySQLBackend(username='******', password='******', database='opsi'))
    mysqlBackend.backend_deleteBase()
    mysqlBackend.backend_createBase()

    def check(one, two):
示例#10
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Manual tests for the HTTPConnectionPool.

:author: Niko Wenselowski <*****@*****.**>
:license: GNU Affero General Public License version 3
"""

import time

from OPSI.Logger import Logger, LOG_DEBUG
from OPSI.Util.HTTP import HTTPSConnectionPool

LOGGER = Logger()


def main():
    pool = HTTPSConnectionPool(
        host='download.uib.de',
        port=443,
        connectTimeout=5,
        # caCertFile='/tmp/xxx',
        # verifyServerCertByCa=True
    )
    resp = pool.urlopen('GET',
                        url='/index.html',
                        body=None,
                        headers={
                            "accept": "text/html",
示例#11
0
from OPSI.Types import *  # this is needed for dynamic extension loading
from OPSI.Util import objectToBeautifiedText, getfqdn  # used in extensions
from OPSI.Util.File.Opsi import BackendACLFile, BackendDispatchConfigFile, OpsiConfFile

if os.name == 'posix':
    import grp
    import PAM
    import pwd
elif os.name == 'nt':
    import win32net
    import win32security

__all__ = ('BackendManager', 'BackendDispatcher', 'BackendExtender',
           'BackendAccessControl', 'backendManagerFactory')

logger = Logger()

try:
    from OPSI.System.Posix import Distribution
    DISTRIBUTOR = Distribution().distributor or 'unknown'
except ImportError:
    # Probably running on Windows.
    DISTRIBUTOR = 'unknown'

try:
    with closing(os.popen('lsb_release -d 2>&1 /dev/null')) as f:
        DISTRIBUTION = f.read().split(':')[1].strip()
except Exception as error:
    logger.debug("Reading Distribution failed: {0}".format(error))
    DISTRIBUTION = 'unknown'
示例#12
0
__version__ = '4.0'

import sys
import os
import getopt
import locale

from OPSI.Types import forceInt, forceFilename, forceUnicode
from OPSI.Util.Message import NotificationClient, SubjectsObserver
from OPSI.Logger import Logger, LOG_NONE, LOG_DEBUG

encoding = locale.getpreferredencoding()
argv = sys.argv

logger = Logger()


class OpsiDialogWindow(SubjectsObserver):
	def __init__(self, port=0, host=u'127.0.0.1', notificationClientId=None):
		self._notificationClient = None
		if port:
			self._notificationClient = NotificationClient(host, port, self, notificationClientId)
			self._notificationClient.addEndConnectionRequestedCallback(self.close)

	def close(self):
		logger.notice("OpsiDialogWindow.close()")

	def setStatusMessage(self, message):
		self.messageChanged({'id': "status", 'type': "faketype"}, message)