Play with WMI objects using python
-
I started learning python
few months ago; I must say it is an awesome language to learn.
-
-
When it comes to system
administration I worked on both Linux and windows, but that is not the point I
want to discuss here!
-
When we talk about Windows
related scripting, it is always about VBscript or PowerShell, so I decided to
see what I should do in Python.
-
Of course, everyone will
say: YOU CAN DO ANYTHING WITH PYTHON! I know that already so please calm down…
-
Just like PowerShell or
VBscript, you can use WMI objects with Python to view or change some setting on
your local or remote Server.
-
To Access WMI objects with
python, first you need to download the “WMI 1.4.9” module in Python.
-
You can install this module
using pip tool, or simply download it from this link : https://pypi.python.org/pypi/WMI/
-
To use pip, you can run
this from the command Prompt: pip install wmi , if you already got this installed, you can
upgrade it using this command : pip install wmi.
-
After installing the
module, you can open an IDLE session and write: import wmi; , if you didn't get any error, that
means it’s imported and working fine.
-
Now let’s get to the point,
the script goes this way :
-
This small piece of code
will simply show as the names of all active process currently on your PC.
-
Now what if we want to do
some change, let’s say, we want to kill a process, we can do it this way :
-
You can see that with this
minor change, instead of using “name” property, instead, we used a method called
“Terminate()” to kill a process called "notepad.exe"
you can find both scripts here :
Code1:
import wmi;
wmivar = wmi.WMI()
q = "select * from win32_process"
for a in wmivar.query(q):
print(a.name)
Code2:
import wmi;
wmivar = wmi.WMI()
q = "select * from win32_process where name='notepad.exe'"
for a in wmivar.query(q):
a.Terminate()
-
Hope this was useful,
Happy scripting, hasta luego todos…