def getWindowsNameInterfaceForMacadress(macadress): obj = utils.simplecommand("wmic NIC get MACAddress,NetConnectionID") for lig in obj['result']: l = lig.lower() mac = macadress.lower() if l.startswith(mac): element = lig.split(' ') element[0] = '' fin = [x for x in element if x.strip() != ""] return " ".join(fin)
def agentinfoversion(xmppobject): """ return information on agent. """ #creation Repport on agent cmd = "python %s -i -v"%(os.path.join(xmppobject.pathagent, "replicator.py")) logger.debug("cmd : %s"%(cmd)) result = simplecommand(cmd) resultobj={} rr = [ x.rstrip() for x in result['result'] ] val= ['testmodule', 'pathagent', 'agentdescriptor', 'pathimg', 'imgdescriptor', 'action', 'other1', 'other2'] boottrap = 0 for t in rr: if t.startswith('--') or t.startswith('__'): continue if t.endswith('pulse_xmpp_agent'): boottrap = boottrap + 1 if t.startswith('{'): boottrap = boottrap + 1 if t.startswith('}'): resultobj[val[boottrap]].append(t.strip()) boottrap = boottrap + 1 continue if not val[boottrap] in resultobj: resultobj[val[boottrap]] = [] resultobj[val[boottrap]].append(t.strip()) testmodule = resultobj['testmodule'][0] information = "".join(resultobj['testmodule'][1:]) agentdescriptor = "".join(resultobj['agentdescriptor']) imgdescriptor = "".join(resultobj['imgdescriptor']) pathimg = resultobj['pathimg'][0] pathagent = resultobj['pathagent'][0] actiontxt = ",".join(resultobj['action']) res={ 'testmodule' : testmodule, 'information' : information, 'pathagent' : pathagent, 'agentdescriptor' : agentdescriptor, 'pathimg' : pathimg, 'imgdescriptor' : imgdescriptor, 'actiontxt' : actiontxt, "conf": xmppobject.config.updating, "plugins" : xmppobject.dataplugininstall} l = json.dumps(res, indent=4) return l
def createjsontree(self): logging.getLogger().debug("Creation hierarchi file") if sys.platform.startswith('win'): cmd ='%s %s %s'%(self.programmetreejson,self.rootfilesystem, self.jsonfile) else: cmd ='%s -r \'%s\' -o "%s"'%(self.programmetreejson, self.rootfilesystem, self.jsonfile) msg = "Generation tree.json command : [%s] "%cmd logging.getLogger().debug("%s : "%cmd) obj = simplecommand(cmd) if obj['code'] != 0 : logger.error(obj['result']) if self.objectxmpp != None: self.objectxmpp.xmpplog("error generate tree for machine %s [cmd :%s]"%(self.objectxmpp.boundjid.bare, cmd), type = 'noset', sessionname = '', priority = 0, action = "", who = self.objectxmpp.boundjid.bare, how = "Remote", why = "", module = "Error| Notify | browsing", fromuser = "", touser = "") return if self.objectxmpp != None: self.objectxmpp.xmpplog("generate tree for machine %s [cmd :%s]"%(self.objectxmpp.boundjid.bare, cmd), type = 'noset', sessionname = '', priority = 0, action = "", who = self.objectxmpp.boundjid.bare, how = "Remote", why = "", module = "Error| Notify | browsing", fromuser = "", touser = "") logger.debug(msg)
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)
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)