Example #1
0
    def getComputersListHeaders(self, ctx):
        __headers = {
            'cn': ['cn', 'Computer Name'],
            'os': ['os', 'Operating System'],
            'description': ['displayName', 'Description'],
            'type': ['type', 'Computer Type'],
            'user': ['user', 'Last Logged User'],
            'owner': ['owner', 'Owner'],
            'owner_firstname': ['owner_firstname', 'Owner Firstname'],
            'owner_realname': ['owner_realname', 'Owner Realname'],
            'inventorynumber': ['inventorynumber', 'Inventory Number'],
            'state': ['state', 'State'],
            'entity': ['entity', 'Entity'],
            'location': ['location', 'Location'],
            'model': ['model', 'Model'],
            'manufacturer': ['manufacturer', 'Manufacturer'],
        }

        # Add registry keys to the computers view if needed
        master_config = xmppMasterConfig()
        regvalue = []
        r = re.compile(r'reg_key_.*')
        regs = filter(r.search, self.config.summary)
        for regkey in regs:
            regkeyconf = getattr(master_config, regkey).split("|")[-1]
            if regkeyconf.startswith('HKEY'):
                regkeyconf = getattr(master_config, regkey).split("\\")[-1]
            __headers[regkey] = [regkey, regkeyconf]

        return [__headers[x] for x in self.config.summary]
Example #2
0
def activate():
    """
    Read the plugin configuration, initialize it, and run some tests to ensure
    it is ready to operate.
    """
    logger = logging.getLogger()
    config = xmppMasterConfig("xmppmaster")
    if config.disable:
        logger.warning("Plugin xmppmaster: disabled by configuration.")
        return False
    if not XmppMasterDatabase().activate(config):
        logger.warning(
            "Plugin XmppMaster: an error occurred during the database initialization"
        )
        return False
    return True
Example #3
0
 def doTask(self):
     tg = xmppMasterConfig()
     if tg.debugmode == "NOTSET":
         tg.debugmode = 0
     elif tg.debugmode == "DEBUG":
         tg.debugmode = 10
     elif tg.debugmode == "INFO":
         tg.debugmode = 20
     if tg.debugmode == "LOG" or tg.debugmode == "DEBUGPULSE":
         tg.debugmode = 25
     elif tg.debugmode == "WARNING":
         tg.debugmode = 30
     elif tg.debugmode == "ERROR":
         tg.debugmode = 40
     elif tg.debugmode == "CRITICAL":
         tg.debugmode = 50
     logging.basicConfig(
         level=tg.debugmode,
         format='[%(name)s.%(funcName)s:%(lineno)d] %(message)s')
     #logging.log(tg.debugmode,"=======================================test log")
     self.xmpp = MUCBot(tg)
     self.xmpp.register_plugin('xep_0030')  # Service Discovery
     self.xmpp.register_plugin('xep_0045')  # Multi-User Chat
     self.xmpp.register_plugin('xep_0004')  # Data Forms
     self.xmpp.register_plugin('xep_0050')  # Adhoc Commands
     self.xmpp.register_plugin('xep_0199', {
         'keepalive': True,
         'frequency': 300,
         'interval': 300,
         'timeout': 200
     })
     self.xmpp.register_plugin('xep_0077')  # Registration
     # xmpp.register_plugin('xep_0047') # In-band Registration
     # xmpp.register_plugin('xep_0096') # file transfer
     # xmpp.register_plugin('xep_0095') # file transfer
     self.xmpp['xep_0077'].force_registration = False
     self.xmpp.register_plugin('xep_0279')
     if tg.Server == "" or tg.Port == "":
         logger.error("Parameters connection server xmpp missing.")
     if self.xmpp.connect(address=(tg.Server, tg.Port)):
         self.xmpp.process(block=True)
         logger.info("done")
     else:
         logger.info("Unable to connect.")
Example #4
0
def action(xmppobject, action, sessionid, data, message, ret, dataobj):
    logging.getLogger().debug(plugin)
    try:
        print json.dumps(data[0], indent=4)
        transpxmpp = True
        if 'taillefile' in data[0]:
            # determine si fichier est transportable dans un message xmppmaster
            if "Mo" in data[0]['taillefile']:
                transpxmpp = False
                print "Mo"
            else:
                if "ko" in data[0]['taillefile']:
                    data[0]['taillefile'] = float(
                        data[0]['taillefile'][:-2]) * 1024
                else:
                    data[0]['taillefile'] = float(data[0]['taillefile'])
                if data[0]['taillefile'] > 256000:
                    transpxmpp = False
    except KeyError as e:
        logging.getLogger().debug(
            "data[0] not found while calling %s. The plugin is probably called from a quick action."
            % (plugin['NAME']))
        pass

    # if transpxmpp:
    # la taille du fichier permet de faire le transfert dans un message xmpp pas encore implemente

    if 'dest' in data and 'src' in data and 'jidmachine' in data:
        jidmachine = data['jidmachine']
        Machineinfo = XmppMasterDatabase().getMachinefromjid(jidmachine)
        dest = data['dest']
        src = data['src']
    else:
        try:
            jidmachine = data[0]['jidmachine']
            Machineinfo = XmppMasterDatabase().getMachinefromjid(jidmachine)
            dest = data[0]['dest']
            src = data[0]['src']
        except KeyError:
            print json.dumps(data, indent=4)
            jidmachine = data['data'][0]
            Machineinfo = XmppMasterDatabase().getMachinefromjid(jidmachine)
            params = data['data'][2]
            if len(params) > 1:
                # if params[1]:
                dest = params[1]
            else:
                machdir = os.path.join(xmppMasterConfig().defaultdir,
                                       Machineinfo['hostname'])
                now = datetime.datetime.now()
                try:
                    # Run on a machine
                    datedir = "%s-%s" % (data['data'][1][1]['user'],
                                         now.strftime("%Y-%m-%d-%H:%M:%S"))
                except KeyError:
                    # Run on a group
                    datedir = "%s-%s" % (data['data'][1]['user'],
                                         now.strftime("%Y-%m-%d-%H:%M:%S"))
                    pass
                destdir = os.path.join(machdir, datedir)
                if not os.path.exists(machdir):
                    os.mkdir(machdir)
                    os.chmod(machdir, 0777)
                if not os.path.exists(destdir):
                    logging.getLogger().debug("Creating folder: %s" % destdir)
                    os.mkdir(destdir)
                if '\\' in params[0]:
                    final_folder = os.path.basename(
                        os.path.normpath(params[0].replace('\\', '/').replace(
                            ':', '')))
                else:
                    final_folder = os.path.basename(os.path.normpath(
                        params[0]))
                dest = os.path.join(destdir, final_folder)
            src = params[0]

    relayserver = XmppMasterDatabase().getMachinefromjid(
        Machineinfo['groupdeploy'])
    relayserinfo = XmppMasterDatabase().getRelayServerfromjid(
        Machineinfo['groupdeploy'])

    print json.dumps(relayserinfo, indent=4)
    datasend = {
        'session_id': sessionid,
        'action': "downloadfile",
        'data': {
            'jidrelayser': Machineinfo['groupdeploy'],
            'path_src_machine': src,
            'path_dest_master': dest,
            'jidmachine': jidmachine,
            # item host is uuid glpi machine
            'host': Machineinfo['uuid_inventorymachine'],
            'ipars': relayserver['ip_xmpp'],
            'ipserverars': relayserinfo['ipserver'],
            'iparspublic': relayserver['ippublic'],
            'package_server_ip': relayserinfo['package_server_ip'],
            'ipmachine': Machineinfo['ip_xmpp'],
            'ipmachinepublic': Machineinfo['ippublic'],
            'ipmaster': str(xmppobject.config.Server),
            'osmachine': Machineinfo['platform'],
            'jidmachine': jidmachine,
            'hostname': Machineinfo['hostname']
        }
    }

    # print json.dumps(datasend, indent = 4)
    try:
        if datasend['data']['ipars'] != str(xmppobject.config.Server):
            cmd = scpfile(
                "root@%s:/root/.ssh/id_rsa.pub" % (datasend['data']['ipars']),
                "/tmp/id_rsa.pub")
            print cmd
            z = simplecommand(cmd)
            # print z['result']
            # print z['code']
            if z['code'] != 0:
                logging.getLogger().warning(z['result'])
                pass
            else:
                dede = file_get_content("/tmp/id_rsa.pub")
                authorized_key = file_get_content("/root/.ssh/authorized_keys")
                # verify key exist in authorized_key for ARS.
                if not dede in authorized_key:
                    logging.getLogger().debug("Add key %s" %
                                              datasend['data']['jidmachine'])
                    file_put_content("/root/.ssh/authorized_keysold",
                                     "\n" + dede,
                                     mode="a")
                    print authorized_key

        # send message to relayserver for get file on machine
        # to ARS
        xmppobject.send_message(mto=Machineinfo['groupdeploy'],
                                mbody=json.dumps(datasend),
                                mtype='chat')

    except Exception as e:
        logging.getLogger().error("Error in plugin %s : %s" %
                                  (plugin['NAME'], str(e)))
        traceback.print_exc(file=sys.stdout)
Example #5
0
 def __init__(self, args=(), kwargs=None):
     threading.Thread.__init__(self)
     self.args = args
     self.kwargs = kwargs
     self.disable = xmppMasterConfig().disable
     self.xmpp = None