def action(xmppobject): logging.getLogger().debug(plugin) try: # read max_key_index parameter to find out the number of keys if hasattr(xmppobject.config, 'max_key_index'): logging.getLogger().debug("Loading %s keys" % xmppobject.config.max_key_index) nb_iter = int(xmppobject.config.max_key_index) + 1 for num in range(1, nb_iter): registry_key = getattr(xmppobject.config, 'reg_key_' + str(num)).split('|')[0] try: registry_key_name = getattr(xmppobject.config, 'reg_key_' + str(num)).split('|')[1] except IndexError: registry_key_name = getattr(xmppobject.config, 'reg_key_' + str(num)).split('\\')[-1] # Check that the keys are in glpi and insert them if not present if not Glpi().getRegistryCollect(registry_key): Glpi().addRegistryCollect(registry_key, registry_key_name) pass except Exception, e: logging.getLogger().error("Error loading plugin: %s" % str(e)) traceback.print_exc(file=sys.stdout) pass
def getAllSoftwaresAndVersions(ctx, softname="", version=None): if version is None: return [x[0] for x in Glpi().getAllSoftwares(ctx, softname=softname)] else: return [ x[0] for x in Glpi().getAllVersion4Software(ctx, softname, version) ]
def query(ctx, criterion, value): logging.getLogger().info(ctx) logging.getLogger().info(criterion) logging.getLogger().info(value) machines = [] if criterion == 'OU user': machines = [x.name for x in Glpi().getMachineByHostname(ctx, value)] elif criterion == 'OU Machine': machines = [x.name for x in Glpi().getMachineByContact(ctx, value)] return [machines, True]
def checkPool(): ret = True try : pool = Glpi().database.db.pool if pool._max_overflow > -1 and pool._overflow >= pool._max_overflow : logging.getLogger().error('glpi plugin: CHECK: NOK: timeout then overflow (%d vs. %d) detected in SQL pool : check your network connectivity !' % (pool._overflow, pool._max_overflow)) pool.dispose() pool = pool.recreate() ret = False except Exception, e: logging.getLogger().warn('glpi plugin: CHECK: NOK: got the following error : %s' % (e)) ret = False
def checkPool(): ret = True try: pool = Glpi().database.db.pool if pool._max_overflow > -1 and pool._overflow >= pool._max_overflow: logging.getLogger().error( 'glpi plugin: CHECK: NOK: timeout then overflow (%d vs. %d) detected in SQL pool : check your network connectivity !' % (pool._overflow, pool._max_overflow)) pool.dispose() pool = pool.recreate() ret = False except Exception, e: logging.getLogger().warn( 'glpi plugin: CHECK: NOK: got the following error : %s' % (e)) ret = False
class GlpiComputers(ComputerI): def __init__(self, conffile=None): self.logger = logging.getLogger() self.config = GlpiConfig("glpi", conffile) self.glpi = Glpi() def getComputer(self, ctx, filt=None): if filt == None or filt == "": filt = {} try: complete_ctx(ctx) location = ctx.locations if type(location) != list and location != None: location = [location] filt["ctxlocation"] = location except exceptions.AttributeError: pass try: return self.glpi.getComputer(ctx, filt) except Exception, e: if len(e.args) > 0 and e.args[0].startswith("NOPERM##"): machine = e.args[0].replace("NOPERM##", "") self.logger.warn( "User %s does not have good permissions to access machine '%s'" % (ctx.userid, machine) ) return False raise e
def activate(): config = GlpiConfig("glpi") logger = logging.getLogger() if config.disable: logger.warning("Plugin glpi: disabled by configuration.") return False if not GlpiLocation().init(config): # does Glpi().activate() return False if not Glpi().db_check(): return False ComputerManager().register("glpi", GlpiComputers) ProvisioningManager().register("glpi", GlpiProvisioner) if config.displayLocalisationBar: ComputerLocationManager().register("glpi", GlpiLocation) if config.check_db_enable: scheduleCheckStatus(config.check_db_interval) # Register the panel to the DashboardManager try: from mmc.plugins.dashboard.manager import DashboardManager from mmc.plugins.glpi.panel import GlpiPanel DM = DashboardManager() DM.register_panel(GlpiPanel("glpi")) except ImportError: pass return True
def getLicensesCount(vendor, software, version, valcount=1): ctx = SecurityContext() ctx.userid = "root" def replace_splat(param): if '*' in param: return param.replace('*', '%') return param def check_param(param): if param == '' or param == '*' or param == '%': return None return replace_splat(param) software = check_param(software) vendor = check_param(vendor) version = check_param(version) if software is None: software = '%' rr = xmlrpcCleanup(Glpi().getAllSoftwaresImproved(ctx, software, vendor=vendor, version=version, count=valcount)) return rr
class GlpiComputers(ComputerI): def __init__(self, conffile=None): self.logger = logging.getLogger() self.config = GlpiConfig("glpi", conffile) self.glpi = Glpi() def getComputer(self, ctx, filt=None, empty_macs=False): if filt == None or filt == '': filt = {} try: complete_ctx(ctx) location = ctx.locations if type(location) != list and location != None: location = [location] filt['ctxlocation'] = location except exceptions.AttributeError: pass try: return self.glpi.getComputer(ctx, filt, empty_macs) except Exception, e: if len(e.args) > 0 and e.args[0].startswith('NOPERM##'): machine = e.args[0].replace('NOPERM##', '') self.logger.warn( "User %s does not have good permissions to access machine '%s'" % (ctx.userid, machine)) return False raise e
def getLastMachineInventoryPart(uuid, part, minbound=0, maxbound=-1, filt=None, options={}): return xmlrpcCleanup(Glpi().getLastMachineInventoryPart( uuid, part, minbound, maxbound, filt, options))
def get_host_rsync_path(uuid): machine_info = Glpi().getLastMachineInventoryFull(uuid) machine = dict((key, value) for (key, value) in machine_info) if 'Windows'.lower() in machine['os'].lower(): if '64' in machine['os_arch']: return 'C:\\Windows\\SysWOW64\\rsync.exe' else: return 'C:\\Windows\\System32\\rsync.exe' elif 'macOS'.lower() in machine['os'].lower(): return 'rsync' else: return '/usr/bin/rsync'
def _cbProvisioning(self, auth, authtoken): """ Provision the MMC user account with ACLs """ if not auth: self.logger.warning( "User authentication with GLPI web interface failed, but going on with provisioning" ) profiles = Glpi().getUserProfiles(authtoken.getLogin()) self.logger.debug("User '%s' GLPI's profiles: %s" % (authtoken.getLogin(), str(profiles))) self.logger.debug("Profiles order (from ini configuration): %s" % (self.config.profilesOrder)) selected = None for profile in self.config.profilesOrder: if profile in profiles: selected = profile break if not selected: self.logger.info("User GLPI's profile can't be applied") else: self.logger.debug("Selected GLPI profile is %s" % selected) try: acls = self.config.profilesAcl[selected.lower()] except KeyError: acls = None if not acls: self.logger.info("No ACL to apply for the GLPI profile %s" % selected) else: l = ldapUserGroupControl() self.logger.info( "Setting MMC ACL corresponding to GLPI profile %s: %s" % (selected, acls)) uid = authtoken.getLogin() entry = l.getDetailedUser(uid) if not "lmcUserObject" in entry["objectClass"]: entry["objectClass"].append("lmcUserObject") l.changeUserAttributes(uid, "objectClass", entry["objectClass"]) l.changeUserAttributes(authtoken.getLogin(), "lmcAcl", acls) return authtoken
def getAllSoftwares(ctx, softname='', vendor=None): def replace_splat(param): if '*' in param: return param.replace('*', '%') return param def check_param(param): if param == '' or param == '*' or param == '%': return None return replace_splat(param) software = check_param(softname) if vendor is not None: vendor = check_param(vendor) if software is None: software = '%' return [x[0] for x in Glpi().getAllSoftwares(ctx, softname=softname, vendor=vendor, limit=20)]
def activate(): config = GlpiConfig("glpi") logger = logging.getLogger() if config.disable: logger.warning("Plugin glpi: disabled by configuration.") return False if not GlpiLocation().init(config): # does Glpi().activate() return False if not Glpi().db_check(): return False ComputerManager().register("glpi", GlpiComputers) ProvisioningManager().register("glpi", GlpiProvisioner) if config.displayLocalisationBar: ComputerLocationManager().register("glpi", GlpiLocation) if config.check_db_enable: scheduleCheckStatus(config.check_db_interval) return True
def getAllSoftwaresAndVersions(ctx, softname="", version=None): ret = [] if version == None: ret = unique([x.name for x in Glpi().getAllSoftwares(ctx, softname)]) else: if Glpi().glpi_chosen_version().find('0.8') == 0: # glpi in 0.8 ret = unique([ x.name for x in Glpi().getAllVersion4Software(ctx, softname, version) ]) else: if Glpi().glpi_version_new(): ret = unique([ x.name for x in Glpi().getAllVersion4Software( ctx, softname, version) ]) else: ret = unique([ x.version for x in Glpi().getAllVersion4Software( ctx, softname, version) ]) ret.sort() return ret
def getAntivirusStatus(self): ctx = self.currentContext return xmlrpcCleanup(Glpi().getAntivirusStatus(ctx))
def getMachineNumberByState(self): ctx = self.currentContext return xmlrpcCleanup(Glpi().getMachineNumberByState(ctx))
def getMachineListByState(self, groupName): ctx = self.currentContext return xmlrpcCleanup(Glpi().getMachineListByState(ctx, groupName))
def get_machines_with_os_and_version(os, version): return xmlrpcCleanup(Glpi().get_machines_with_os_and_version(os, version))
class exportedReport(object): def __init__(self): self.db = Glpi() self.ctx = SecurityContext() self.ctx.userid = "root" def _getEntitiesIds(self, entities=[]): """ Return a list of entities ids for the request @param entitites: a list of entities uuids @return: list of entities ids """ # Be sure to get all entities self.ctx.locations = None if hasattr(self.ctx, 'locationsid'): del self.ctx.locationsid # get all entities uuids for the current user if entities == []: entities = [entity.toH()['uuid'] for entity in self.db.getAllEntities(self.ctx)] return [fromUUID(str(entity)) for entity in entities] def _getComputerCountByOSes(self, entities, os_names, results, oper=operator.add): os_results = [] if os_names: for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] os_count = self.db.getMachineByOsLike(self.ctx, os_names, count=1) os_results.append({'entity_id': entity, 'value': os_count}) for os_result in os_results: count = False for result in results: if os_result['entity_id'] == result['entity_id']: if result['value'] is not None and os_result['value'] is not None: result['value'] = oper(result['value'], os_result['value']) else: result['value'] = 0 count = True if not count and oper == operator.add: results.append(os_result) return results def getComputerCountByOSes(self, entities, os_names, exclude_names=[]): """ Get computer count for os_names @param os_names: list of OS names to count @param exclude_names: list of OS names to exclude @return: count of machines by entity """ if isinstance(os_names, basestring): os_names = [os_names] os_names = [os_name.replace('*', '%') for os_name in os_names] exclude_names = [exclude_name.replace('*', '%') for exclude_name in exclude_names] results = self._getComputerCountByOSes(entities, os_names, []) results = self._getComputerCountByOSes(entities, exclude_names, results, operator.sub) return results def getAllComputerCount(self, entities): """ Count all computers by entity """ results = [] for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] count = self.db.getRestrictedComputersListLen(self.ctx) results.append({'entity_id': entity, 'value': count}) return results def getComputerCountByTypes(self, entities, types): """ Get computer count for types @param types: list of computer types to count @return: count of machines by entity """ if isinstance(types, basestring): types = [types] types = [type.replace("*", "%") for type in types] results = [] if types: for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] type_count = self.db.getMachineByType(self.ctx, types, count=1) results.append({'entity_id': entity, 'value': type_count}) return results def getComputerCountByState(self, entities, state): result = [] state = state.replace("*", "%") for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] state_count = self.db.getMachineByState(self.ctx, state, count=1) result.append({'entity_id': entity, 'value': state_count}) return result def _constructSoftwareTuple(self, soft): """ @param soft: string or dict @return: software tuple: (name, version, vendor) """ name = version = vendor = None if soft and isinstance(soft, basestring): name = soft.replace('*', '%') elif type(soft) == dict: name = soft.get('name', None) if name: name = name.replace('*', '%') version = soft.get('version', None) if version: version = version.replace('*', '%') vendor = soft.get('vendor', None) if vendor: vendor = vendor.replace('*', '%') if name is None: logger.error("Missing software name") return None return (name, version, vendor) def _constructSoftwaresList(self, softs): """ @param softs: dict, string, list of mixed string and dict @return: list of software tuples [(name, version, vendor), (name, version, vendor), (name, version, vendor), ...] """ if type(softs) == list: return [self._constructSoftwareTuple(soft) for soft in softs] if softs: return [self._constructSoftwareTuple(softs)] return [] def _getComputerCountBySoftwares(self, entities, softs, results, oper=operator.add): soft_results= [] if softs: for entity in self._getEntitiesIds(entities): self.ctx.locationsid = [entity] soft_count = self.db.getAllSoftwaresImproved(self.ctx, [soft[0] for soft in softs], version=[soft[1] for soft in softs], vendor=[soft[2] for soft in softs], count=1) soft_results.append({'entity_id': entity, 'value': soft_count}) for soft_result in soft_results: count = False for result in results: if soft_result['entity_id'] == result['entity_id']: if result['value'] is not None and soft_result['value'] is not None: result['value'] = oper(result['value'], soft_result['value']) else: result['value'] = 0 count = True if not count and oper == operator.add: results.append(soft_result) return results def getComputerCountBySoftwares(self, entities, soft_names, exclude_names={}): """ Get computer count for software names @param soft_names: list of softwares to count @param exclude_names: list of softwares to exclude soft_names can be a simple string (ie: 'Mozilla Firefox*') soft_names can be a dict (ie: {'name': 'Mozilla Firefox', 'version': '24.0', vendor:'Mozilla'}) soft_names can be a list of mixed dict and strings Same for exclude_names @return: count of machines by entity """ softs = self._constructSoftwaresList(soft_names) excludes = self._constructSoftwaresList(exclude_names) results = self._getComputerCountBySoftwares(entities, softs, []) results = self._getComputerCountBySoftwares(entities, excludes, results, operator.sub) return results
def __init__(self, conffile=None): self.logger = logging.getLogger() self.config = GlpiConfig("glpi", conffile) self.glpi = Glpi()
def get_os_for_dashboard(): return xmlrpcCleanup(Glpi().get_os_for_dashboard())
def getAllEntitiesPowered(*args, **kwargs): return xmlrpcCleanup(Glpi().getAllEntitiesPowered(*args, **kwargs))
def moveEntityRuleDown(*args, **kwargs): return xmlrpcCleanup(Glpi().moveEntityRuleDown(*args, **kwargs))
def addLocation(*args, **kwargs): return xmlrpcCleanup(Glpi().addLocation(*args, **kwargs))
def editLocation(*args, **kwargs): return xmlrpcCleanup(Glpi().editLocation(*args, **kwargs))
def setUserPassword(*args, **kwargs): return xmlrpcCleanup(Glpi().setUserPassword(*args, **kwargs))
def deleteEntityRule(*args, **kwargs): return xmlrpcCleanup(Glpi().deleteEntityRule(*args, **kwargs))
def __init__(self): self.db = Glpi() self.ctx = SecurityContext() self.ctx.userid = "root"
def getRestrictedComputersListLen(self): ctx = self.currentContext return Glpi().getRestrictedComputersListLen(ctx, {})
def get_all_uuids_and_hostnames(): return Glpi().get_all_uuids_and_hostnames()
def addEntityRule(*args, **kwargs): return xmlrpcCleanup(Glpi().addEntityRule(*args, **kwargs))
def action(xmppobject, action, sessionid, data, message, ret, dataobj): logging.getLogger().debug(plugin) sessionid = name_random(5, "wakeonlan") try: listserverrelay = XmppMasterDatabase().listserverrelay() if 'macadress' in data: senddataplugin = { 'action': 'wakeonlan', 'sessionid': sessionid, 'data': { 'macaddress': data['macadress'] } } for serverrelay in listserverrelay: xmppobject.send_message(mto=serverrelay[0], mbody=json.dumps(senddataplugin, encoding='latin1'), mtype='chat') xmppobject.xmpplog("ARS %s : WOL for macadress %s" % (serverrelay[0], data['macadress']), type='deploy', sessionname=sessionid, priority=-1, action="", who="", how="", why=xmppobject.boundjid.bare, module="Wol | Start | Creation", date=None, fromuser=xmppobject.boundjid.bare, touser="") elif 'UUID' in data: listadressmacs = Glpi().getMachineMac(data['UUID']) for macadress in listadressmacs: if macadress == '00:00:00:00:00:00': continue senddataplugin = { 'action': 'wakeonlan', 'sessionid': sessionid, 'data': { 'macaddress': macadress } } for serverrelay in listserverrelay: xmppobject.send_message(mto=serverrelay[0], mbody=json.dumps( senddataplugin, encoding='latin1'), mtype='chat') xmppobject.xmpplog("ARS %s : WOL for macadress %s" % (serverrelay[0], macadress), type='deploy', sessionname=sessionid, priority=-1, action="", who="", how="", why=xmppobject.boundjid.bare, module="Wol | Start | Creation", date=None, fromuser=xmppobject.boundjid.bare, touser="") else: raise except: print "error plugin plugin_wakeonlan %s" % data traceback.print_exc(file=sys.stdout)
def editEntityRule(*args, **kwargs): return xmlrpcCleanup(Glpi().editEntityRule(*args, **kwargs))