コード例 #1
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")
コード例 #2
0
    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)
コード例 #3
0
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!?"
コード例 #4
0
ファイル: winpdh.py プロジェクト: remind101/integrations-core
    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
コード例 #5
0
    def _make_counter_path(self, machine_name, counter_name, instance_name, counters):
        '''
        When handling non english versions, the counters don't work quite as documented.
        This is because strings like "Bytes Sent/sec" might appear multiple times in the
        english master, and might not have mappings for each index.

        Search each index, and make sure the requested counter name actually appears in
        the list of available counters; that's the counter we'll use.
        '''
        path = ""
        if WinPDHCounter._use_en_counter_names:
            '''
            In this case, we don't have any translations.  Just attempt to make the
            counter path
            '''
            try:
                path = win32pdh.MakeCounterPath((machine_name, self._class_name, instance_name, None, 0, counter_name))
                self.logger.debug("Successfully created English-only path")
            except Exception as e: # noqa: E722
                self.logger.warning("Unable to create English-only path %s" % str(e))
                raise
            return path

        counter_name_index_list = WinPDHCounter.pdh_counter_dict[counter_name]

        for index in counter_name_index_list:
            c = win32pdh.LookupPerfNameByIndex(None, int(index))
            if c is None or len(c) == 0:
                self.logger.debug("Index %s not found, skipping" % index)
                continue

            # check to see if this counter is in the list of counters for this class
            if c not in counters:
                try:
                    self.logger.debug("Index %s counter %s not in counter list" % (index, unicode(c)))
                except: # noqa: E722
                    # some unicode characters are not translatable here.  Don't fail just
                    # because we couldn't log
                    self.logger.debug("Index %s not in counter list" % index)
                    pass

                continue

            # see if we can create a counter
            try:
                path = win32pdh.MakeCounterPath((machine_name, self._class_name, instance_name, None, 0, c))
                self.logger.debug("Successfully created path %s" % index)
                break
            except: # noqa: E722
                try:
                    self.logger.info("Unable to make path with counter %s, trying next available" % unicode(c))
                except: # noqa: E722
                    self.logger.info("Unable to make path with counter index %s, trying next available" % index)
                    pass
        return path
コード例 #6
0
ファイル: monitor.py プロジェクト: moraygrieve/pysys
	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
コード例 #7
0
ファイル: process.py プロジェクト: ewdriver/NSightAgent
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)
コード例 #8
0
ファイル: winpdh.py プロジェクト: umisora/dd-agent
    def __init__(self, class_name, instance_name, log):
        self._get_counter_dictionary()
        self._class_name = win32pdh.LookupPerfNameByIndex(
            None, int(WinPDHCounter.pdh_counter_dict[class_name]))
        self._instance_name = win32pdh.LookupPerfNameByIndex(
            None, int(WinPDHCounter.pdh_counter_dict[instance_name]))

        self._is_single_instance = False
        self.hq = win32pdh.OpenQuery()
        self.logger = log
        self.counterdict = {}
        counters, instances = win32pdh.EnumObjectItems(
            None, None, self._class_name, win32pdh.PERF_DETAIL_WIZARD)
        if len(instances) > 0:
            for inst in instances:
                path = win32pdh.MakeCounterPath((None, self._class_name, inst,
                                                 None, 0, self._instance_name))
                try:
                    self.counterdict[inst] = win32pdh.AddCounter(self.hq, path)
                except:
                    self.logger.fatal(
                        "Failed to create counter.  No instances of %s\%s" %
                        (self._class_name, self._instance_name))
                try:
                    self.logger.debug("Path: %s\n" % unicode(path))
                except:
                    # 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:
            path = win32pdh.MakeCounterPath(
                (None, self._class_name, None, None, 0, self._instance_name))
            try:
                self.logger.debug("Path: %s\n" % unicode(path))
            except:
                # 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:
                self.logger.fatal(
                    "Failed to create counter.  No instances of %s\%s" %
                    (self._class_name, self._instance_name))
                raise
            self._is_single_instance = True
コード例 #9
0
    def FindChildrenOf(self, parentid):

        childPids = []

        object = "Process"
        items, instances = win32pdh.EnumObjectItems(
            None, None, object, win32pdh.PERF_DETAIL_WIZARD)

        instance_dict = {}
        for instance in instances:
            if instance in instance_dict:
                instance_dict[instance] += 1
            else:
                instance_dict[instance] = 0

        for instance, max_instances in instance_dict.items():
            for inum in range(max_instances + 1):
                hq = win32pdh.OpenQuery()
                try:
                    hcs = []

                    path = win32pdh.MakeCounterPath(
                        (None, object, instance, None, inum, "ID Process"))
                    hcs.append(win32pdh.AddCounter(hq, path))

                    path = win32pdh.MakeCounterPath(
                        (None, object, instance, None, inum,
                         "Creating Process ID"))
                    hcs.append(win32pdh.AddCounter(hq, path))

                    try:
                        # If the process goes away unexpectedly this call will fail
                        win32pdh.CollectQueryData(hq)

                        type, pid = win32pdh.GetFormattedCounterValue(
                            hcs[0], win32pdh.PDH_FMT_LONG)
                        type, ppid = win32pdh.GetFormattedCounterValue(
                            hcs[1], win32pdh.PDH_FMT_LONG)

                        if int(ppid) == parentid:
                            childPids.append(int(pid))
                    except:
                        pass

                finally:
                    win32pdh.CloseQuery(hq)

        return childPids
コード例 #10
0
def test_localized_global(aggregator, dd_run_check, mock_performance_objects):
    import win32pdh

    mock_performance_objects({'Foo': (['baz'], {'Bar': [9000]})})
    check = get_check(
        {'metrics': {
            'Foo': {
                'name': 'foo',
                'counters': [{
                    'Bar': 'bar'
                }]
            }
        }}, {'use_localized_counters': True})
    dd_run_check(check)

    tags = ['instance:baz']
    tags.extend(GLOBAL_TAGS)
    aggregator.assert_metric('test.foo.bar', 9000, tags=tags)

    aggregator.assert_all_metrics_covered()
    aggregator.assert_service_check('test.windows.perf.health',
                                    ServiceCheck.OK,
                                    tags=['server:{}'.format(SERVER)])

    win32pdh.AddCounter.assert_called_once_with(
        mock.ANY,
        win32pdh.MakeCounterPath((SERVER, 'Foo', 'baz', None, 0, 'Bar')))
コード例 #11
0
ファイル: win32pdhquery.py プロジェクト: FlowkoHinti/Dionysos
 def getinstpaths(self,
                  object,
                  counter,
                  machine=None,
                  objtype='Process',
                  format=win32pdh.PDH_FMT_LONG):
     '''
     ### Not an end-user function
     Calculate the paths for an instance object. Should alter
     to allow processing for lists of object-counter pairs.
     '''
     items, instances = win32pdh.EnumObjectItems(None, None, objtype, -1)
     # find out how many instances of this element we have...
     instances.sort()
     try:
         cur = instances.index(object)
     except ValueError:
         return []  # no instances of this object
     temp = [object]
     try:
         while instances[cur + 1] == object:
             temp.append(object)
             cur = cur + 1
     except IndexError:  # if we went over the end
         pass
     paths = []
     for ind in range(len(temp)):
         # can this raise an error?
         paths.append(
             win32pdh.MakeCounterPath(
                 (machine, 'Process', object, None, ind, counter)))
     return paths  # should also return the number of elements for naming purposes
コード例 #12
0
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
コード例 #13
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
コード例 #14
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)
コード例 #15
0
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)
コード例 #16
0
ファイル: utils.py プロジェクト: yaitskov/nupic
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
コード例 #17
0
ファイル: WinProcesses.py プロジェクト: raychorn/chrome_gui
 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
コード例 #18
0
ファイル: count_processes.py プロジェクト: Sloop0/fairgame
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
コード例 #19
0
ファイル: win32pdhutil.py プロジェクト: FlowkoHinti/Dionysos
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)
コード例 #20
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
コード例 #21
0
    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)
コード例 #22
0
ファイル: htx_wifi.py プロジェクト: YiJie0430/AM_HIVE_TCP
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)
コード例 #23
0
	def rawaddcounter(self,object, counter, instance = None, inum=-1, machine=None):
		'''
		Adds a single counter path, without catching any exceptions.
		
		See addcounter for details.
		'''
		path = win32pdh.MakeCounterPath( (machine,object,instance, None, inum,counter) )
		self.paths.append(path)
コード例 #24
0
    def open(self, hq):
        """Open a counter request from an already open win32pdh query.
        """

        self.path = win32pdh.MakeCounterPath(
            (self.machine, self.object, self.instance, None, self.inum,
             self.counter))
        self.hc = win32pdh.AddCounter(hq, self.path)
コード例 #25
0
 def __init__(self, class_name, instance_name):
     WinPDHCounter.__init__(self, class_name, instance_name)
     self.counterdict = {}
     counters, instances = win32pdh.EnumObjectItems(
         None, None, self._class_name, win32pdh.PERF_DETAIL_WIZARD)
     for inst in instances:
         path = win32pdh.MakeCounterPath(
             (None, self._class_name, inst, None, 0, self._instance_name))
         self.counterdict[inst] = win32pdh.AddCounter(self.hq, path)
コード例 #26
0
ファイル: service.py プロジェクト: pimvanriezen/n2
    def getnetwork(self, netquery=None):
        # FIXME: takes first nic instead of total
        if not self.netquery:
            self.netquery = win32pdh.OpenQuery()
            iface = win32pdh.EnumObjectItems(None, None, 'Network Interface', win32pdh.PERF_DETAIL_WIZARD, 0)[1][0]
            rxpath = win32pdh.MakeCounterPath( (None, 'Network Interface', iface, None, 0, 'Bytes Received/sec') )
            txpath = win32pdh.MakeCounterPath( (None, 'Network Interface', iface, None, 0, 'Bytes Sent/sec') )
            self.nethandles = (
              win32pdh.AddCounter(self.netquery, rxpath),
              win32pdh.AddCounter(self.netquery, txpath)
            )
            win32pdh.CollectQueryData(self.netquery)
            
        win32pdh.CollectQueryData(self.netquery)

        discard, rx = win32pdh.GetFormattedCounterValue(self.nethandles[0], win32pdh.PDH_FMT_LONG)
        discard, tx = win32pdh.GetFormattedCounterValue(self.nethandles[1], win32pdh.PDH_FMT_LONG)
        return rx, tx
コード例 #27
0
    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')
コード例 #28
0
ファイル: wininfo.py プロジェクト: 584250550/pyRat-1
 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
コード例 #29
0
 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
コード例 #30
0
def construct_counter_path(*,
                           machine_name,
                           object_name,
                           counter_name,
                           instance_name=None,
                           instance_index=0):
    # More info: https://docs.microsoft.com/en-us/windows/win32/perfctrs/specifying-a-counter-path
    #
    # https://docs.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhmakecounterpatha
    # https://mhammond.github.io/pywin32/win32pdh__MakeCounterPath_meth.html
    return win32pdh.MakeCounterPath((machine_name, object_name, instance_name,
                                     None, instance_index, counter_name))