def initialisekiosk(data, message, xmppobject):
    machine = XmppMasterDatabase().getMachinefromjid(message['from'])
    if "userlist" and "oumachine" and "ouuser" in data:
        if len(data['userlist']) == 0:
            user = ""
        else:
            user = data['userlist'][0]
        print "call updatemachineAD"
        XmppMasterDatabase().updatemachineAD(machine['id'], user,
                                             data['oumachine'], data['ouuser'])

    print json.dumps(machine, indent=4)
    initializationdatakiosk = handlerkioskpresence(
        message['from'],
        machine['id'],
        machine['platform'],
        machine['hostname'],
        machine['uuid_inventorymachine'],
        machine['agenttype'],
        classutil=machine['classutil'],
        fromplugin=True)

    datasend = {
        "sessionid": name_random(6, "initialisation_kiosk"),
        "action": "kiosk",
        "data": initializationdatakiosk
    }
    xmppobject.send_message(mto=message['from'],
                            mbody=json.dumps(datasend),
                            mtype='chat')
Example #2
0
def action(xmppobject, action, sessionid, data, message, ret, dataobj):
    logging.getLogger().debug(plugin)
    try:
        relayserver = XmppMasterDatabase().getRelayServerForMachineUuid(
            data['uuid'])
        jidmachine = XmppMasterDatabase().getjidMachinefromuuid(data['uuid'])
        senddataplugin = {
            'action': 'guacamole',
            'sessionid': name_random(5, "guacamole"),
            'data': {
                'jidmachine': jidmachine,
                'cux_id': data['cux_id'],
                'cux_type': data['cux_type'],
                'uuid': data['uuid']
            }
        }
        xmppobject.send_message(mto=relayserver['jid'],
                                mbody=json.dumps(senddataplugin,
                                                 encoding='latin1'),
                                mtype='chat')

    except:
        logging.getLogger().error("error plugin plugin_guacamole %s" % data)
        traceback.print_exc(file=sys.stdout)
        pass
Example #3
0
def runXmppAsyncCommand(cmd, infomachine):
    sessionid = name_random(8, "quick_")
    cmd = cmd.strip()
    if cmd.startswith("plugin_"):
        # call plugin master
        lineplugincalling = [x.strip() for x in cmd.split("@_@")]
        plugincalling = lineplugincalling[0]
        del lineplugincalling[0]
        action = plugincalling.strip().split("_")
        action.pop(0)
        action = "_".join(action)
        data = {
            "action": action,
            "sessionid": sessionid,
            "data": [infomachine['jid'], infomachine, lineplugincalling]
        }
        XmppMasterDatabase().setCommand_action(
            infomachine['uuid_inventorymachine'], infomachine['cmdid'],
            sessionid, "call plugin %s for Quick Action" % (action), "log")
        callXmppPlugin(action, data)
    else:
        data = {
            "action": "asynchroremoteQA",
            "sessionid": sessionid,
            "data": infomachine,
            "base64": False
        }
        callXmppPlugin("asynchroremoteQA", data)
def action(xmppobject, action, sessionid, data, message, ret, dataobj):
    logging.getLogger().debug(plugin)

    advanced = data['advanced']
    try:
        result = XmppMasterDatabase().checkstatusdeploy(advanced['idcmd'])
        advanced['actionscheduler'] = result  # abandonmentdeploy, run or pause
        datasend = {
            'action': data['fromaction'],
            'sessionid': sessionid,
            'data': advanced,
            'ret': 0,
            'base64': False
        }
        xmppobject.send_message(mto=message['from'],
                                mbody=json.dumps(datasend),
                                mtype='chat')
    except Exception as e:
        print "Error in plugin %s" % str(e)
        traceback.print_exc(file=sys.stdout)
        advanced['actionscheduler'] = "error"  # abandonmentdeploy, run or pause
        datasend = {
            'action': data['fromaction'],
            'sessionid': sessionid,
            'data': advanced,
            'ret': 0,
            'base64': False
        }
        xmppobject.send_message(mto=message['from'],
                                mbody=json.dumps(datasend),
                                mtype='chat')
Example #5
0
def getdeploybyuserpast(login, duree, min=None, max=None, filt=None):
    if min == "":
        min = None
    if max == "":
        max = None
    return XmppMasterDatabase().getdeploybyuserpast(login, duree, min, max,
                                                    filt)
Example #6
0
def callInventoryinterface(uuid):
    jid = XmppMasterDatabase().getjidMachinefromuuid(uuid)
    if jid != "":
        callInventory(jid)
        return jid
    else:
        logging.getLogger().error("for machine %s : jid xmpp missing" % uuid)
        return "jid missing"
Example #7
0
def adddeployabort(idcommand, jidmachine, jidrelay, host, inventoryuuid,
                   uuidpackage, state, sessionid, user, login, title,
                   group_uuid, startcmd, endcmd, macadress):
    return XmppMasterDatabase().adddeploy(idcommand, jidmachine, jidrelay,
                                          host, inventoryuuid, uuidpackage,
                                          state, sessionid, user, login, title,
                                          group_uuid, startcmd, endcmd,
                                          macadress)
def action(xmppobject, action, sessionid, data, message, ret, dataobj):
    logging.getLogger().debug(plugin)
    try:
        logging.getLogger().debug("End deploy command : %s" % data['idcmd'])
        XmppMasterDatabase().updatedeployinfo(data['idcmd'])
    except Exception as e:
        logging.getLogger().error("Error in plugin %s" % str(e))
        pass
Example #9
0
def callshutdown(uuid, time, msg):
    jid = XmppMasterDatabase().getjidMachinefromuuid(uuid)
    if jid != "":
        callshutdownbymaster(jid, time, msg)
        return jid
    else:
        logging.getLogger().error(
            "callshutdownbymaster for machine %s : jid xmpp missing" % uuid)
        return "jid missing"
Example #10
0
def addlogincommand(login, commandid, grpid, nb_machine_in_grp,
                    instructions_nb_machine_for_exec,
                    instructions_datetime_for_exec, parameterspackage,
                    rebootrequired, shutdownrequired, limit_rate_ko, params):
    return XmppMasterDatabase().addlogincommand(
        login, commandid, grpid, nb_machine_in_grp,
        instructions_nb_machine_for_exec, instructions_datetime_for_exec,
        parameterspackage, rebootrequired, shutdownrequired, limit_rate_ko,
        params)
def action(xmppobject, action, sessionid, data, message, ret, objsessiondata):
    logging.getLogger().debug(plugin)
    try:
        XmppMasterDatabase().addlistguacamoleidforiventoryid(
            data['uuid'], data['connection'])
    except Exception, e:
        logging.getLogger().error("Error: %s" % str(e))
        traceback.print_exc(file=sys.stdout)
        pass
Example #12
0
def callrestart(uuid):
    jid = XmppMasterDatabase().getjidMachinefromuuid(uuid)
    if jid != "":
        callrestartbymaster(jid)
        return jid
    else:
        logging.getLogger().error(
            "callrestartbymaster for machine %s : jid xmpp missing" % uuid)
        return "jid missing"
Example #13
0
def setCommand_qa(command_name,
                  command_action,
                  command_login,
                  command_grp="",
                  command_machine='',
                  command_os=""):
    return XmppMasterDatabase().setCommand_qa(command_name, command_action,
                                              command_login, command_grp,
                                              command_machine, command_os)
Example #14
0
def callvncchangeperms(uuid, askpermission):
    jid = XmppMasterDatabase().getjidMachinefromuuid(uuid)
    if jid != "":
        callvncchangepermsbymaster(jid, askpermission)
        return jid
    else:
        logging.getLogger().error(
            "callvncchangepermsbymaster for machine %s : jid xmpp missing" %
            uuid)
        return "jid missing"
def action(xmppobject, action, sessionid, data, message, ret, objsessiondata):
    logger.debug("#################################################")
    logger.debug(plugin)
    logger.debug("#################################################")
    try:
        XmppMasterDatabase().addlistguacamoleidforiventoryid(
            data['uuid'], data['connection'])
    except Exception, e:
        logger.error("plugin resultguacamoleconf Error: %s" % str(e))
        #logger.error("\n%s"%(traceback.format_exc()))
        pass
Example #16
0
def getLogxmpp(start_date, end_date, typelog, action, module, user, how, who,
               why, headercolumn):
    if typelog == "None" and action == "None" and module == "None" and start_date == "":
        return []
    if typelog == "None":
        typelog == ""
    if module == "None":
        module == ""
    if action == "None":
        action == ""
    return XmppMasterDatabase().getLogxmpp(start_date, end_date, typelog,
                                           action, module, user, how, who, why,
                                           headercolumn)
Example #17
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 #18
0
def get_machine_stop_deploy(cmdid, uuid):
    result = XmppMasterDatabase().get_machine_stop_deploy(cmdid, uuid)
    msg_stop_deploy = {
        "action": "enddeploy",
        "sessionid": result['sessionid'],
        'data': {
            "typerequest": "bansessionid"
        },
        "ret": 0,
        'base64': False
    }
    updatedeploystate(result['sessionid'], 'DEPLOYMENT ABORT')
    if 'jid_relay' in result and result['jid_relay'] != "fake_jidrelay":
        send_message_json(result['jid_relay'], msg_stop_deploy)
    if 'jidmachine' in result and result['jidmachine'] != "fake_jidmachine":
        send_message_json(result['jidmachine'], msg_stop_deploy)
    return True
def action(xmppobject, action, sessionid, data, message, ret, dataobj):
    logging.getLogger().debug(
        "=====================================================")
    logging.getLogger().debug(plugin)
    logging.getLogger().debug(
        "=====================================================")
    try:
        XmppMasterDatabase().setCommand_action(
            data['data']['data']['uuid_inventorymachine'],
            data['data']['data']['cmdid'],
            sessionid,
            "".join(data['result']['result']),
            typemessage="result")

        print json.dumps(data, indent=4)
    except Exception, e:
        logging.getLogger().error("Error loading plugin: %s" % str(e))
        traceback.print_exc(file=sys.stdout)
        pass
Example #20
0
def action(xmppobject, action, sessionid, data, message, ret, dataobj):
    logging.getLogger().debug(
        "=====================================================")
    logging.getLogger().debug(plugin)
    logging.getLogger().debug(
        "=====================================================")
    try:
        if ret == 0:
            logger.debug("Succes deploy on %s Package "\
                ": %s Session : %s" % (data['jidmachine'],
                                       data['descriptor']['info']['name'],
                                       sessionid))
            XmppMasterDatabase().delete_resources(sessionid)
        else:
            logger.error("Error deploy on %s Package "\
                ": %s Session : %s" % (data['jidmachine'],
                                       data['descriptor']['info']['name'],
                                       sessionid))
    except:
        logger.error("%s" % (traceback.format_exc()))
Example #21
0
def get_group_stop_deploy(grpid, cmdid):
    result = XmppMasterDatabase().get_group_stop_deploy(grpid, cmdid)
    msg_stop_deploy = {
        "action": "enddeploy",
        "sessionid": "",
        'data': {
            "typerequest": "bansessionid"
        },
        "ret": 0,
        'base64': False
    }
    for machine in result['objectdeploy']:
        msg_stop_deploy['sessionid'] = machine['sessionid']
        updatedeploystate1(machine['sessionid'], 'DEPLOYMENT ABORT')
        if 'jid_relay' in machine and machine['jid_relay'] != "fake_jidrelay":
            send_message_json(machine['jid_relay'], msg_stop_deploy)
        if 'jidmachine' in machine and machine[
                'jidmachine'] != "fake_jidmachine":
            send_message_json(machine['jidmachine'], msg_stop_deploy)
    return True
Example #22
0
def getlistcommandforuserbyos(login,
                              osname=None,
                              min=None,
                              max=None,
                              filt=None,
                              edit=None):
    if osname == '':
        osname = None
    if min == '':
        min = None
    if max == '':
        max = None
    if filt == '':
        filt = None
    if edit == '':
        edit = None

    return XmppMasterDatabase().getlistcommandforuserbyos(login,
                                                          osname=osname,
                                                          min=min,
                                                          max=max,
                                                          filt=filt,
                                                          edit=edit)
Example #23
0
def getshowmachinegrouprelayserver():
    def Nonevalue(x):
        if x == None:
            return ""
        else:
            return x

    machinelist = XmppMasterDatabase().showmachinegrouprelayserver()
    array = []
    for t in machinelist:
        z = [Nonevalue(x) for x in list(t)]
        ob = {
            'jid': z[0],
            'type': z[1],
            'os': z[2],
            'rsdeploy': z[3],
            'hostname': z[4],
            'uuid': z[5],
            'ip': z[6],
            'subnet': z[7]
        }
        array.append(ob)
    return array
Example #24
0
def getCommand_qa_by_cmdid(cmdid):
    return XmppMasterDatabase().getCommand_qa_by_cmdid(cmdid)
def action(xmppobject, action, sessionid, data, message, ret, dataobj):
    logging.getLogger().debug(
        "=====================================================")
    logging.getLogger().debug(plugin)
    logging.getLogger().debug(
        "=====================================================")

    data = data[0]
    print json.dumps(data, indent=4)

    if 'dest' in data and 'directory' in data and 'listfile' in data and 'jidmachine' in data:
        jidmachine = data['jidmachine']
        try:
            #### reduit enregistrement
            listdirectory = [
                x.strip() for x in data['listdirectory'].split(";")
                if x.strip() != ""
            ]
            listfile = [
                x.strip() for x in data['listfile'].split(";")
                if x.strip() != ""
            ]
            listdirectory.sort()
            listfile.sort()

            remfile = []
            for i in listdirectory:
                for t in listfile:
                    if i in t:
                        remfile.append(t)
            for t in list(set(remfile)):
                listfile.remove(t)

            dd = []
            a = 0
            nb = len(listdirectory)
            for y in range(nb - 1):
                if y > a: a = y
                for index in range(a + 1, nb):
                    if listdirectory[a] in listdirectory[index]:
                        dd.append(listdirectory[index])

            for t in list(set(dd)):
                listdirectory.remove(t)

        except Exception as e:
            logging.getLogger().error("Error in plugin %s" % (str(e)))
            traceback.print_exc(file=sys.stdout)

        Machineinfo = XmppMasterDatabase().getMachinefromjid(jidmachine)
        #dest =
        #src = data['src']
        relayserver = XmppMasterDatabase().getMachinefromjid(
            Machineinfo['groupdeploy'])
        relayserinfo = XmppMasterDatabase().getRelayServerfromjid(
            Machineinfo['groupdeploy'])
        print "relayserver"
        print json.dumps(relayserver, indent=4)
        print "relayserinfo"
        print json.dumps(relayserinfo, indent=4)

        if str(Machineinfo['platform']).startswith('Linux') or str(
                Machineinfo['platform']).startswith('darwin'):
            separator = "/"
        else:
            separator = "\\"
        listdirstr = []
        for t in listdirectory:
            if t.lower() != "c:\\\\" and t.lower() != "d:\\\\":
                listdirstr.append("%s%s" % (t, separator))
            else:
                listdirstr.append(t)

        datasend = {
            'session_id': sessionid,
            'action': "downloadfileexpert",
            'data': {
                'jidrelayser': Machineinfo['groupdeploy'],
                'path_src_machine_dir': listdirstr,
                'path_src_machine_file': listfile,
                'path_dest_master': data['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']
            }
        }

    # On permet au relay server d'ecrire sur master en ssh.
    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")
            z = simplecommand(cmd)
            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")
        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 #26
0
def getlinelogssession(sessionxmpp):
    return XmppMasterDatabase().getlinelogssession(sessionxmpp)
Example #27
0
def get_list_of_users_for_shared_qa(namecmd):
    return XmppMasterDatabase().get_list_of_users_for_shared_qa(namecmd)
Example #28
0
def getCountOnlineMachine():
    return XmppMasterDatabase().getCountOnlineMachine()
Example #29
0
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)
Example #30
0
def getQAforMachine(cmd_id, uuidmachine):
    resultdata = XmppMasterDatabase().getQAforMachine(cmd_id, uuidmachine)
    if resultdata[0][3] == "result":
        # encode 64 str? to transfer xmlrpc if string with sequence escape
        resultdata[0][4] = base64.b64encode(resultdata[0][4])
    return resultdata