November 12, 2008

Get CPU Utilization from Remote Windows Machines with WMI

This is a little script that gets the CPU Utilization metric from a remote Windows machine. On multi-way or multi-core machines, it will return an average of all processors/cores.

To run this, you will first need to install the WMI module. Follow the instructions and get the download from here: http://timgolden.me.uk/python/wmi.html

import wmi

def get_cpu(computer, user, password):
    c = wmi.WMI(find_classes=False, computer=computer, user=user, password=password)
    utilizations = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
    utilization = int(sum(utilizations) / len(utilizations))
    return utilization

5 comments:

Unknown said...

You could do something like c.Win32_Processor(Name='_Total')[0].LoadPercentage to get it in one go.

Unknown said...

Actually, you might want to double check that you're not indluding the total as a CPU in your list. I think it might be, but then it won't be changing the average I guess...

Anonymous said...

Just in case you don't know you can also query WMI from Linux with wmic (Which is in fact a python importable module) I write a wrapper around it, but I didn't know it at the time so my code uses subprocess to call it...

In case it's of any interest:

http://felimwhiteley.wordpress.com/2008/10/01/using-python-to-retrieve-wmi-data-using-wmic/

Unknown said...

Hi Felim,

You say wmic is importable by python? But how? I can get /usr/bin/wmic and /usr/bin/winexe when installing wmi-client.

Pavan said...

How do we run this script?