def __init__(self,
                 ffprocess,
                 process,
                 counters=None,
                 childProcess="plugin-container"):
        self.ffprocess = ffprocess
        self.childProcess = childProcess
        self.registeredCounters = {}
        self.registerCounters(counters)
        # PDH might need to be "refreshed" if it has been queried while the browser
        # is closed
        win32pdh.EnumObjects(None, None, 0, 1)

        # Add the counter path for the default process.
        for counter in self.registeredCounters:
            path = win32pdh.MakeCounterPath(
                (None, 'process', process, None, -1, counter))
            hq = win32pdh.OpenQuery()
            try:
                hc = win32pdh.AddCounter(hq, path)
            except:
                win32pdh.CloseQuery(hq)
                #assume that this is a memory counter for the system, not a process counter
                path = win32pdh.MakeCounterPath(
                    (None, 'Memory', None, None, -1, counter))
                hq = win32pdh.OpenQuery()
                try:
                    hc = win32pdh.AddCounter(hq, path)
                except:
                    win32pdh.CloseQuery(hq)

            self.registeredCounters[counter] = [hq, [(hc, path)]]
            self.updateCounterPathsForChildProcesses(counter)
Beispiel #2
0
    def __init__(self):
        processor = win32pdhutil.find_pdh_counter_localized_name("Processor")
        processorTime = win32pdhutil.find_pdh_counter_localized_name("% Processor Time")

        path = win32pdh.MakeCounterPath((None,processor,"_Total", None, -1, processorTime))
        self.base = win32pdh.OpenQuery()
        self.__counter = win32pdh.AddCounter(self.base, path)
        win32pdh.CollectQueryData(self.base)
        # the function addCounter change the locale to the current locale (french ?)
        # and implies problems of float to string conversion (.5 => "0,5")
        locale.setlocale(locale.LC_ALL, None)
        self.__processorLoad = 0
        
        
        MEMORY = "Memory"
        COMMBYTES = "Available Bytes"
        memory = win32pdhutil.find_pdh_counter_localized_name(MEMORY)
        commbytes = win32pdhutil.find_pdh_counter_localized_name(COMMBYTES)

        path_comm = win32pdh.MakeCounterPath((None, memory, None, None, -1, commbytes))         
        self.base2 = win32pdh.OpenQuery()
        self.__counter2 = win32pdh.AddCounter(self.base2, path_comm)
        win32pdh.CollectQueryData(self.base2)
        # the function addCounter change the locale to the current locale (french ?)
        # and implies problems of float to string conversion (.5 => "0,5")
        locale.setlocale(locale.LC_ALL, None)

        self.__processorLoad = 0
        self.__availableMemory = 0
        
        locale.setlocale(locale.LC_ALL, "C")
Beispiel #3
0
	def __win32LogProfile(self, instance, inum, threads, interval, file):
		
		# create the process performance counters
		process_counters=[]
		process_query=win32pdh.OpenQuery()
		for counter in "Working Set", "Virtual Bytes", "Private Bytes", "Thread Count", "Handle Count":
			path = win32pdh.MakeCounterPath( (None, "Process", instance, None, inum, counter) )
			process_counters.append(win32pdh.AddCounter(process_query, path))
		win32pdh.CollectQueryData(process_query)
					
		# create the thread performance counter
		thread_counters=[]
		thread_query=win32pdh.OpenQuery()
		for (instance, inum) in threads:
			path=win32pdh.MakeCounterPath( (None, "Thread", instance, None, inum, "% Processor Time") )
			thread_counters.append(win32pdh.AddCounter(thread_query, path))
		win32pdh.CollectQueryData(thread_query)
	
		# perform the continual data collection until the thread is no longer active
		data = [0]*(len(process_counters)+1)	
		try:
			while self.active:
				win32pdh.CollectQueryData(process_query)
				win32pdh.CollectQueryData(thread_query)
	
				for i in range(len(process_counters)):
					try:
						data[i+1] = win32pdh.GetFormattedCounterValue(process_counters[i], win32pdh.PDH_FMT_LONG)[1]
					except win32api.error:
						data[i+1] = -1
			
				data[0]=0
				for i in range(0, len(thread_counters)):
					try:
						data[0]=data[0]+win32pdh.GetFormattedCounterValue(thread_counters[i], win32pdh.PDH_FMT_LONG)[1] 
					except Exception:
						pass
		
				currentTime = time.strftime("%d/%m/%y %H:%M:%S", time.gmtime(time.time()))
				file.write( "%s\t%s\t%d\t%d\t%d\t%d\t%d\n" % (currentTime, data[0]//self.numProcessors, float(data[1])/1024,
														  float(data[2])/1024, float(data[3])/1024, float(data[4]), float(data[5])))
				file.flush()
				time.sleep(interval)
		finally:
			# clean up
			for c in process_counters:
				win32pdh.RemoveCounter(c)
			win32pdh.CloseQuery(process_query)
			for c in thread_counters:
				win32pdh.RemoveCounter(c)
			win32pdh.CloseQuery(thread_query)
			if file != sys.stdout: file.close()
			self.active = 0
Beispiel #4
0
    def get_counter_val(counter_path, *args, **kwargs):
        try:
            sleep = float(kwargs['sleep'][0])
        except (KeyError, TypeError, IndexError):
            sleep = 0

        query = win32pdh.OpenQuery()
        try:
            counter = win32pdh.AddCounter(query, counter_path)
            try:
                win32pdh.CollectQueryData(query)
                if sleep != 0:
                    time.sleep(sleep)
                    win32pdh.CollectQueryData(query)
                _, _, _, _, _, _, _, info, _ = win32pdh.GetCounterInfo(counter, False)
                _, value = win32pdh.GetFormattedCounterValue(counter, win32pdh.PDH_FMT_DOUBLE)
            finally:
                win32pdh.RemoveCounter(counter)
        finally:
            win32pdh.CloseQuery(query)

        unit = info[-1]

        if not isinstance(value, (int, long)):
            value = round(value, 2)

        return [value, unit]
Beispiel #5
0
 def open(self):
     '''
     Build the base query object for this wrapper,
     then add all of the counters required for the query.
     Raise a QueryError if we can't complete the functions.
     If we are already open, then do nothing.
     '''
     if not self.active:  # to prevent having multiple open queries
         # curpaths are made accessible here because of the possibility of volatile paths
         # which may be dynamically altered by subclasses.
         self.curpaths = copy.copy(self.paths)
         try:
             base = win32pdh.OpenQuery()
             for path in self.paths:
                 try:
                     self.counters.append(win32pdh.AddCounter(base, path))
                 except win32api.error:  # we passed a bad path
                     self.counters.append(0)
                     pass
             self._base = base
             self.active = 1
             return 0  # open succeeded
         except:  # if we encounter any errors, kill the Query
             try:
                 self.killbase(base)
             except NameError:  # failed in creating query
                 pass
             self.active = 0
             self.curpaths = []
             raise QueryError(self)
     return 1  # already open
def GetProcessID ( name ) :
  if os.name != 'nt' :
    return None
  else:
    import win32pdh
    import time
    object = "Process"
    items, instances = win32pdh.EnumObjectItems(None,None,object, win32pdh.PERF_DETAIL_WIZARD)

    val = None
    if name in instances :
      hq = win32pdh.OpenQuery()
      hcs = []
      item = "ID Process"
      path = win32pdh.MakeCounterPath( (None,object,name, None, 0, item) )
      hcs.append(win32pdh.AddCounter(hq, path))
      win32pdh.CollectQueryData(hq)
      time.sleep(0.01)
      win32pdh.CollectQueryData(hq)

      for hc in hcs:
        type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG)
        win32pdh.RemoveCounter(hc)
      win32pdh.CloseQuery(hq)
    return val
def FindMyCounter():
    pid_me = win32api.GetCurrentProcessId()

    object = "Process"
    items, instances = win32pdh.EnumObjectItems(None, None, object, -1)
    for instance in instances:
        # We use 2 counters - "ID Process" and "Working Set"
        counter = "ID Process"
        format = win32pdh.PDH_FMT_LONG

        hq = win32pdh.OpenQuery()
        path = win32pdh.MakeCounterPath(
            (None, object, instance, None, -1, "ID Process"))
        hc1 = win32pdh.AddCounter(hq, path)
        path = win32pdh.MakeCounterPath(
            (None, object, instance, None, -1, "Working Set"))
        hc2 = win32pdh.AddCounter(hq, path)
        win32pdh.CollectQueryData(hq)
        type, pid = win32pdh.GetFormattedCounterValue(hc1, format)
        if pid == pid_me:
            win32pdh.RemoveCounter(hc1)  # not needed any more
            return hq, hc2
        # Not mine - close the query and try again
        win32pdh.RemoveCounter(hc1)
        win32pdh.RemoveCounter(hc2)
        win32pdh.CloseQuery(hq)
    else:
        raise RuntimeError, "Can't find myself!?"
Beispiel #8
0
def ShowAllProcesses():
    object = find_pdh_counter_localized_name("Process")
    items, instances = win32pdh.EnumObjectItems(None, None, object,
                                                win32pdh.PERF_DETAIL_WIZARD)
    # Need to track multiple instances of the same name.
    instance_dict = {}
    for instance in instances:
        try:
            instance_dict[instance] = instance_dict[instance] + 1
        except KeyError:
            instance_dict[instance] = 0

    # Bit of a hack to get useful info.
    items = [find_pdh_counter_localized_name("ID Process")] + items[:5]
    print("Process Name", ",".join(items))
    for instance, max_instances in instance_dict.items():
        for inum in range(max_instances + 1):
            hq = win32pdh.OpenQuery()
            hcs = []
            for item in items:
                path = win32pdh.MakeCounterPath((None, object, instance,
                                                 None, inum, item))
                hcs.append(win32pdh.AddCounter(hq, path))
            win32pdh.CollectQueryData(hq)
            # as per http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938, some "%" based
            # counters need two collections
            time.sleep(0.01)
            win32pdh.CollectQueryData(hq)
            print("%-15s\t" % (instance[:15]), end=' ')
            for hc in hcs:
                type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG)
                print("%5d" % (val), end=' ')
                win32pdh.RemoveCounter(hc)
            print()
            win32pdh.CloseQuery(hq)
Beispiel #9
0
def procids():
    #each instance is a process, you can have multiple processes w/same name
    junk, instances = win32pdh.EnumObjectItems(None, None, 'process',
                                               win32pdh.PERF_DETAIL_WIZARD)
    proc_ids = []
    proc_dict = {}
    for instance in instances:
        if instance in proc_dict:
            proc_dict[instance] = proc_dict[instance] + 1
        else:
            proc_dict[instance] = 0
    for instance, max_instances in proc_dict.items():
        for inum in xrange(max_instances + 1):
            hq = win32pdh.OpenQuery()  # initializes the query handle
            path = win32pdh.MakeCounterPath(
                (None, 'process', instance, None, inum, 'ID Process'))
            counter_handle = win32pdh.AddCounter(hq, path)
            win32pdh.CollectQueryData(hq)  #collects data for the counter
            type, val = win32pdh.GetFormattedCounterValue(
                counter_handle, win32pdh.PDH_FMT_LONG)
            proc_ids.append((instance, str(val)))
            win32pdh.CloseQuery(hq)

    proc_ids.sort()
    return proc_ids
Beispiel #10
0
def isProcessRunning(pid):
    if sys.platform == "win32":
        # First get a list of all processes. All we get is the process name
        ignoreme, processNames = win32pdh.EnumObjectItems(
            None, None, 'process', win32pdh.PERF_DETAIL_WIZARD)
        processCounts = {}
        for name in processNames:
            if name in processCounts:
                processCounts[name] = processCounts[name] + 1
            else:
                processCounts[name] = 0

        # For each process, get the pid. Stop if we find our PID
        found = False
        for name, nprocs in processCounts.items():
            if found:
                break
            for procNum in xrange(0, nprocs + 1):
                hq = win32pdh.OpenQuery()
                path = win32pdh.MakeCounterPath(
                    (None, 'process', name, None, procNum, 'ID Process'))
                counter_handle = win32pdh.AddCounter(hq, path)
                win32pdh.CollectQueryData(hq)
                type, val = win32pdh.GetFormattedCounterValue(
                    counter_handle, win32pdh.PDH_FMT_LONG)
                win32pdh.CloseQuery(hq)
                if val == pid:
                    found = True
                    break
        return found
    else:
        # unix
        psoutput = runCommandCaptureOutput("ps -p %s" % pid, True)
        return len(psoutput) >= 2
Beispiel #11
0
def GetProcesses():
    win32pdh.EnumObjects(None, None, win32pdh.PERF_DETAIL_WIZARD)
    junk, instances = win32pdh.EnumObjectItems(None,None,'Process', win32pdh.PERF_DETAIL_WIZARD )
    proc_dict = {}
    for instance in instances:
        if proc_dict.has_key(instance):
            proc_dict[instance] = proc_dict[instance] + 1
        else:
            proc_dict[instance]=0
    proc_ids = []
    for instance, max_instances in proc_dict.items():
        for inum in xrange(max_instances+1):
            hq = win32pdh.OpenQuery() # initializes the query handle
            try:
                path = win32pdh.MakeCounterPath( (None, 'Process', instance, None, inum, 'ID Process') )
                counter_handle=win32pdh.AddCounter(hq, path) #convert counter path to counter handle
                try:
                    win32pdh.CollectQueryData(hq) #collects data for the counter
                    type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)
                    proc_ids.append((instance, val))
                except win32pdh.error, e:
                    print e
                win32pdh.RemoveCounter(counter_handle)
            except win32pdh.error, e:
                print e
            win32pdh.CloseQuery (hq)
    def getProcessPrefix(self, pid):
        object = "Process"
        items, instances = win32pdh.EnumObjectItems(
            None, None, object, win32pdh.PERF_DETAIL_WIZARD)
        # Need to track multiple instances of the same name.
        instance_dict = {}
        for instance in instances:
            try:
                instance_dict[instance] = instance_dict[instance] + 1
            except KeyError:
                instance_dict[instance] = 0

        # Bit of a hack to get useful info.
        item = "ID Process"
        for instance, max_instances in instance_dict.items():
            for inum in xrange(max_instances + 1):
                hq = win32pdh.OpenQuery()
                try:
                    hcs = []
                    path = win32pdh.MakeCounterPath(
                        (None, object, instance, None, inum, item))
                    hc = win32pdh.AddCounter(hq, path)
                    try:
                        win32pdh.CollectQueryData(hq)
                        type, val = win32pdh.GetFormattedCounterValue(
                            hc, win32pdh.PDH_FMT_LONG)
                        if val == pid:
                            return "\\".join(path.split("\\")[:-1]) + "\\"
                    finally:
                        win32pdh.RemoveCounter(hc)
                finally:
                    win32pdh.CloseQuery(hq)
Beispiel #13
0
 def fget(self):
     import win32pdh
     object = 'Process'
     items, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD)
     instance_dict = {}
     for instance in instances:
         try:
             instance_dict[instance] = instance_dict[instance] + 1
         except KeyError:
             instance_dict[instance] = 0
     procs = []
     for instance, max_instances in instance_dict.items():
         t = []
         for inum in xrange(max_instances+1):
             hq = win32pdh.OpenQuery()
             hcs = []
             for item in ['ID Process', 'Creating Process ID']:
                 path = win32pdh.MakeCounterPath((None,object,instance,None,inum,item))
                 hcs.append(win32pdh.AddCounter(hq,path))
             win32pdh.CollectQueryData(hq)
             t.append(instance)
             for hc in hcs:
                 type,val=win32pdh.GetFormattedCounterValue(hc,win32pdh.PDH_FMT_LONG)
                 t.append(val)
                 win32pdh.RemoveCounter(hc)
             win32pdh.CloseQuery(hq)
         procs.append(t)
     return procs
def mem_used():
    counter = r'\Memory\Committed Bytes'
    machine, object, instance, parentInstance, index, counter = win32pdh.ParseCounterPath(
        counter)

    instance = None
    inum = -1
    format = win32pdh.PDH_FMT_DOUBLE
    machine = None

    path = win32pdh.MakeCounterPath(
        (machine, object, instance, None, inum, counter))
    hq = win32pdh.OpenQuery()
    try:
        hc = win32pdh.AddCounter(hq, path)
        try:
            win32pdh.CollectQueryData(hq)
            type, val = win32pdh.GetFormattedCounterValue(hc, format)
            return int(val / 1024)
        except pywintypes.error:
            return 0
        finally:
            win32pdh.RemoveCounter(hc)
    finally:
        win32pdh.CloseQuery(hq)
Beispiel #15
0
 def GetPerformanceAttributes(object,
                              counter,
                              instance=None,
                              inum=-1,
                              format=None,
                              machine=None):
     # NOTE: Many counters require 2 samples to give accurate results,
     # including "% Processor Time" (as by definition, at any instant, a
     # thread's CPU usage is either 0 or 100).  To read counters like this,
     # you should copy this function, but keep the counter open, and call
     # CollectQueryData() each time you need to know.
     # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
     # My older explanation for this was that the "AddCounter" process forced
     # the CPU to 100%, but the above makes more sense :)
     import win32pdh
     if format is None: format = win32pdh.PDH_FMT_LONG
     path = win32pdh.MakeCounterPath(
         (machine, object, instance, None, inum, counter))
     hq = win32pdh.OpenQuery()
     try:
         hc = win32pdh.AddCounter(hq, path)
         try:
             win32pdh.CollectQueryData(hq)
             type, val = win32pdh.GetFormattedCounterValue(hc, format)
             return val
         finally:
             win32pdh.RemoveCounter(hc)
     finally:
         win32pdh.CloseQuery(hq)
Beispiel #16
0
def process_list_nt():
    # each instance is a process, you can have multiple processes w/same name
    processLocalizedName = win32pdhutil.find_pdh_counter_localized_name(
        "Process")
    junk, instances = win32pdh.EnumObjectItems(None, None,
                                               processLocalizedName,
                                               win32pdh.PERF_DETAIL_WIZARD)
    proc_ids = {}
    proc_dict = {}
    for instance in instances:
        if instance in proc_dict:
            proc_dict[instance] = proc_dict[instance] + 1
        else:
            proc_dict[instance] = 0
    idProcessLocalizedName = win32pdhutil.find_pdh_counter_localized_name(
        "ID Process")
    for instance, max_instances in list(proc_dict.items()):
        for inum in range(max_instances + 1):
            hq = win32pdh.OpenQuery()  # initializes the query handle
            path = win32pdh.MakeCounterPath(
                (None, processLocalizedName, instance, None, inum,
                 idProcessLocalizedName))
            counter_handle = win32pdh.AddCounter(hq, path)
            win32pdh.CollectQueryData(hq)  # collects data for the counter
            type, val = win32pdh.GetFormattedCounterValue(
                counter_handle, win32pdh.PDH_FMT_LONG)
            proc_ids[str(val)] = instance
            win32pdh.CloseQuery(hq)

    return proc_ids
Beispiel #17
0
 def querysinglecounter(self, path, fmt):
     h = win32pdh.OpenQuery()
     c = win32pdh.AddCounter(h, path)
     win32pdh.CollectQueryData(h)
     discard, v = win32pdh.GetFormattedCounterValue(c, fmt)
     win32pdh.CloseQuery(h)
     return v
Beispiel #18
0
def count_processes():
    object = 'Process'
    items, instances = win32pdh.EnumObjectItems(None, None, object,
                                                win32pdh.PERF_DETAIL_WIZARD)
    instance_dict = {}
    for instance in instances:
        try:
            instance_dict[instance] = instance_dict[instance] + 1
        except KeyError:
            instance_dict[instance] = 0
    counters = {}
    hcs = []
    hq = win32pdh.OpenQuery()
    for instance, max_instances in instance_dict.items():
        for inum in range(max_instances + 1):
            if instance == 'chrome':
                path = win32pdh.MakeCounterPath((None, object, instance, None,
                                                 inum, 'Creating Process ID'))
                hcs.append(win32pdh.AddCounter(hq, path))
    win32pdh.CollectQueryData(hq)
    for hc in hcs:
        try:
            type, val = win32pdh.GetFormattedCounterValue(
                hc, win32pdh.PDH_FMT_LONG)
        except win32pdh.counter_status_error:
            pass
        try:
            counters[val] += 1
        except KeyError:
            counters[val] = 1
        win32pdh.RemoveCounter(hc)
    win32pdh.CloseQuery(hq)
    return counters
Beispiel #19
0
    def connect(self):
        if self.network_resource is not None:
            self.network_resources.add(self.network_resource, self.username,
                                       self.password)

        # https://docs.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhopenquerya
        # https://mhammond.github.io/pywin32/win32pdh__OpenQuery_meth.html
        self.__query_handle = win32pdh.OpenQuery()
Beispiel #20
0
    def __init__(self, class_name, counter_name, log, instance_name = None, machine_name = None, precision=None):
        self._get_counter_dictionary()
        self._class_name = win32pdh.LookupPerfNameByIndex(None, int(WinPDHCounter.pdh_counter_dict[class_name]))
        self._counter_name = win32pdh.LookupPerfNameByIndex(None, int(WinPDHCounter.pdh_counter_dict[counter_name]))

        self._is_single_instance = False
        self.hq = win32pdh.OpenQuery()
        self.logger = log
        self.counterdict = {}
        if precision is None:
            self._precision = win32pdh.PDH_FMT_DOUBLE
        else:
            self._precision = precision
        counters, instances = win32pdh.EnumObjectItems(None, machine_name, self._class_name, win32pdh.PERF_DETAIL_WIZARD)
        if instance_name is None and len(instances) > 0:
            for inst in instances:
                path = win32pdh.MakeCounterPath((machine_name, self._class_name, inst, None, 0, self._counter_name))
                try:
                    self.counterdict[inst] = win32pdh.AddCounter(self.hq, path)
                except: # noqa: E722
                    self.logger.fatal("Failed to create counter.  No instances of %s\%s" % (
                        self._class_name, self._counter_name))
                try:
                    self.logger.debug("Path: %s\n" % unicode(path))
                except: # noqa: E722
                    # some unicode characters are not translatable here.  Don't fail just
                    # because we couldn't log
                    self.logger.debug("Failed to log path")
                    pass
        else:
            if instance_name is not None:
                # check to see that it's valid
                if len(instances) <= 0:
                    self.logger.error("%s doesn't seem to be a multi-instance counter, but asked for specific instance %s" % (
                        class_name, instance_name
                    ))
                    return
                if instance_name not in instances:
                    self.logger.error("%s is not a counter instance in %s" % (
                        instance_name, class_name
                    ))
                    return
            path = win32pdh.MakeCounterPath((machine_name, self._class_name, instance_name, None, 0, self._counter_name))
            try:
                self.logger.debug("Path: %s\n" % unicode(path))
            except: # noqa: E722
                # some unicode characters are not translatable here.  Don't fail just
                # because we couldn't log
                self.logger.debug("Failed to log path")
                pass
            try:
                self.counterdict[SINGLE_INSTANCE_KEY] = win32pdh.AddCounter(self.hq, path)
            except: # noqa: E722
                self.logger.fatal("Failed to create counter.  No instances of %s\%s" % (
                    self._class_name, self._counter_name))
                raise
            self._is_single_instance = True
Beispiel #21
0
    def getcpu(self):
        if not self.cpuquery:
            self.cpuquery = win32pdh.OpenQuery()
            self.cpuhandle = win32pdh.AddCounter(self.cpuquery, r'\Processor(_Total)\% Idle Time')
            win32pdh.CollectQueryData(self.cpuquery)

        win32pdh.CollectQueryData(self.cpuquery)
        discard, val = win32pdh.GetFormattedCounterValue(self.cpuhandle, win32pdh.PDH_FMT_DOUBLE)
        return 100.0 - val
Beispiel #22
0
def main(argv):
    scheduler = BlockingScheduler()

    global hq
    hq = win32pdh.OpenQuery()

    counters, instances = win32pdh.EnumObjectItems(None, None, 'Process', win32pdh.PERF_DETAIL_WIZARD)

    proc_num = {}
    for instance in instances:

        if instance == '_Total' or instance == 'Idle' or instance == 'System':
            continue

        if instance in proc_num:
            proc_num[instance] = proc_num[instance] + 1
        else:
            proc_num[instance] = 1

        for instance in proc_num:
            num = proc_num[instance]
            for id in xrange(num):
                instance_with_id = '%s#%d' % (instance, id)
                counter_dict[instance_with_id] = {}

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'ID Process'))
                counter_dict[instance_with_id]['proc_id'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, '% Processor Time'))
                counter_dict[instance_with_id]['cpu_usert'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Elapsed Time'))
                counter_dict[instance_with_id]['cpu_tm_ss'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Page Faults/sec'))
                counter_dict[instance_with_id]['pf'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Priority Base'))
                counter_dict[instance_with_id]['prit_rnk'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Thread Count'))
                counter_dict[instance_with_id]['thd_cnt'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Private Bytes'))
                counter_dict[instance_with_id]['vir_mem_byt_cnt'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Creating Process ID'))
                counter_dict[instance_with_id]['parent_pid'] = win32pdh.AddCounter(hq, path)

                path = win32pdh.MakeCounterPath((None, 'Process', instance, None, id, 'Handle Count'))
                counter_dict[instance_with_id]['svc_tm'] = win32pdh.AddCounter(hq, path)

    scheduler.add_job(query, 'cron', minute='*/1', second='0')
    scheduler.start()

    win32pdh.CloseQuery(hq)
    def get_processes_dict(self):
        """
        returns a dictionary that contains all the processes PIDs as keys and names as values.
        :return: processes dictionary as described above.
        """

        try:
            # Getting all processes name
            z, proc_name = win32pdh.EnumObjectItems(None, None, self.process_obj, win32pdh.PERF_DETAIL_WIZARD)# PERF_DETAIL_WIZARD = 400
            instances = {}
            for instance in proc_name:
                if instance in instances:
                    instances[instance] += 1
                else:
                    instances[instance] = 1
            proc_pid_name = {}
            for instance, max_instances in instances.items():
                for inum in xrange(max_instances + 1):
                    try:
                        hq = win32pdh.OpenQuery()  # initializes the query handle
                        path = win32pdh.MakeCounterPath((None, self.process_obj, instance, None, inum, self.item))
                        counter_handle = win32pdh.AddCounter(hq, path)  # convert counter path to counter handle
                        win32pdh.CollectQueryData(hq)  # collects data for the counter
                        type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)

                        proc_pid_name[val] = [instance]

                        win32pdh.CloseQuery(hq)
                    except:
                        raise OSError("Problem getting process id")

            return proc_pid_name

        except:
            try:
                from win32com.client import GetObject
                WMI = GetObject('winmgmts:')  # COM object
                proc_instances = WMI.InstancesOf('Win32_Process')  # WMI instanse

                proc_name = [process.Properties_('Name').Value for process in
                             proc_instances]  # Get the processess names

                proc_id = [process.Properties_('ProcessId').Value for process in
                           proc_instances]  # Get the processess names

                proc_pid_name = {}

                proc_id_counter = 0
                for instance in range(len(proc_name)):
                    proc_pid_name[proc_id[instance]] = [(proc_name[instance])]
                    proc_id_counter += 1

                return proc_pid_name

            except:
                raise OSError('Counldnt get the process list')
Beispiel #24
0
def get_counters(counter_list):
    """
    Get the values for the passes list of counters

    Args:
        counter_list (list):
            A list of counters to lookup

    Returns:
        dict: A dictionary of counters and their values
    """
    if not isinstance(counter_list, list):
        raise CommandExecutionError("counter_list must be a list of tuples")

    try:
        # Start a Query instances
        query = win32pdh.OpenQuery()

        # Build the counters
        counters = build_counter_list(counter_list)

        # Add counters to the Query
        for counter in counters:
            counter.add_to_query(query)

        # https://docs.microsoft.com/en-us/windows/desktop/perfctrs/collecting-performance-data
        win32pdh.CollectQueryData(query)
        # The sleep here is required for counters that require more than 1
        # reading
        time.sleep(1)
        win32pdh.CollectQueryData(query)
        ret = {}

        for counter in counters:
            try:
                ret.update({counter.path: counter.value()})
            except pywintypes.error as exc:
                if exc.strerror == "No data to return.":
                    # Some counters are not active and will throw an error if
                    # there is no data to return
                    continue
                else:
                    raise

    except pywintypes.error as exc:
        if exc.strerror == "No data to return.":
            # Sometimess, win32pdh.CollectQueryData can err
            # so just ignore it
            return {}
        else:
            raise

    finally:
        win32pdh.CloseQuery(query)

    return ret
Beispiel #25
0
 def systemUptime(self):
     path = win32pdh.MakeCounterPath(
         (None, r'System', None, None, 0, "System Up Time"))
     query = win32pdh.OpenQuery()
     handle = win32pdh.AddCounter(query, path)
     win32pdh.CollectQueryData(query)
     seconds = win32pdh.GetFormattedCounterValue(
         handle, win32pdh.PDH_FMT_LONG | win32pdh.PDH_FMT_NOSCALE)[1]
     uptime = seconds / 3600
     return uptime
Beispiel #26
0
    def __init__(self,
                 en_class_name,
                 en_counter_name,
                 log,
                 instance_name=None,
                 machine_name=None,
                 precision=None):
        self.counterdict = {}
        self.logger = log
        self._counter_name = en_counter_name
        self._en_class_name = en_class_name
        self._instance_name = instance_name
        self._machine_name = machine_name
        self._is_single_instance = False

        if precision is None:
            self._precision = win32pdh.PDH_FMT_DOUBLE
        else:
            self._precision = precision

        class_name_index_list = []
        try:
            self._get_counter_dictionary()
            class_name_index_list = WinPDHCounter.pdh_counter_dict[
                en_class_name]
        except WindowsError:
            WinPDHCounter._use_en_counter_names = True
            self.logger.warning(
                "Unable to get counter translations; attempting default English names"
            )
        except Exception as e:
            self.logger.error("Exception loading counter strings %s", str(e))
            raise

        if WinPDHCounter._use_en_counter_names:
            self._class_name = en_class_name
        else:
            if len(class_name_index_list) == 0:
                self.logger.warning(
                    "Class %s was not in counter name list, attempting english counter",
                    en_class_name)
                self._class_name = en_class_name
            else:
                if len(class_name_index_list) > 1:
                    self.logger.warning(
                        "Class %s had multiple (%d) indices, using first",
                        en_class_name, len(class_name_index_list))
                self._class_name = win32pdh.LookupPerfNameByIndex(
                    None, int(class_name_index_list[0]))

        self.hq = win32pdh.OpenQuery()
        self.collect_counters()

        if len(self.counterdict) == 0:
            raise AttributeError("No valid counters to report")
 def getcpuload():
     cpupath = win32pdh.MakeCounterPath(
         (None, 'Processor', '_Total', None, -1, '% Processor Time'))
     query = win32pdh.OpenQuery(None, 0)
     counter = win32pdh.AddCounter(query, cpupath, 0)
     win32pdh.CollectQueryData(query)
     time.sleep(0.1)
     win32pdh.CollectQueryData(query)
     status, value = win32pdh.GetFormattedCounterValue(
         counter, win32pdh.PDH_FMT_LONG)
     return float(value) / 100.0
Beispiel #28
0
        def getProcessInstance(self, pid):
            '''
			Get the process instance name using pid.
			'''

            hq = None
            counter_handle = None

            try:

                win32pdh.EnumObjects(None, None, win32pdh.PERF_DETAIL_WIZARD)
                junk, instances = win32pdh.EnumObjectItems(
                    None, None, 'Process', win32pdh.PERF_DETAIL_WIZARD)

                proc_dict = {}
                for instance in instances:
                    if proc_dict.has_key(instance):
                        proc_dict[instance] = proc_dict[instance] + 1
                    else:
                        proc_dict[instance] = 0

                proc_ids = []
                for instance, max_instances in proc_dict.items():
                    for inum in xrange(max_instances + 1):
                        hq = win32pdh.OpenQuery(
                        )  # initializes the query handle
                        try:
                            path = win32pdh.MakeCounterPath(
                                (None, 'Process', instance, None, inum,
                                 'ID Process'))
                            counter_handle = win32pdh.AddCounter(
                                hq,
                                path)  #convert counter path to counter handle
                            try:
                                win32pdh.CollectQueryData(
                                    hq)  #collects data for the counter
                                type, val = win32pdh.GetFormattedCounterValue(
                                    counter_handle, win32pdh.PDH_FMT_LONG)
                                proc_ids.append((instance, val))

                                if val == pid:
                                    return "%s#%d" % (instance, inum)

                            except win32pdh.error, e:
                                #print e
                                pass

                            win32pdh.RemoveCounter(counter_handle)
                            counter_handle = None

                        except win32pdh.error, e:
                            #print e
                            pass
Beispiel #29
0
   def __init__(self):
      maestro.core.IServicePlugin.__init__(self)

      if os.name == 'nt':
         self.mPdhQuery = win32pdh.OpenQuery(None, 0)
         self.mProcPath = win32pdh.MakeCounterPath((None, "Processor", "_Total", None, 0, "% Processor Time"))
         self.mProcCounter = win32pdh.AddCounter(self.mPdhQuery, self.mProcPath, 0)
         try:
            self.update()
         except:
            pass
      else:
         self.mLastCPUTime = [0,0,0,0]
Beispiel #30
0
    def getdiskio(self):
        if not self.diskioquery:
            self.diskioquery = win32pdh.OpenQuery()
            self.diskiohandles = (
              win32pdh.AddCounter(self.diskioquery, r'\PhysicalDisk(_Total)\Disk Read Bytes/sec'),
              win32pdh.AddCounter(self.diskioquery, r'\PhysicalDisk(_Total)\Disk Write Bytes/sec')
            )
            win32pdh.CollectQueryData(self.diskioquery)

        win32pdh.CollectQueryData(self.diskioquery)
        discard, r = win32pdh.GetFormattedCounterValue(self.diskiohandles[0], win32pdh.PDH_FMT_LONG)
        discard, w = win32pdh.GetFormattedCounterValue(self.diskiohandles[1], win32pdh.PDH_FMT_LONG)
        return r+w