Use Python to play with WMI

Source: Internet
Author: User
Tags ldap

When I recently searched the web for Python and WMI, I found that most of the articles were stereotyped and basically only used in a very basic way, and did not explain in depth how to use WMI. This article is going to go a step further and let's use Python to play WMI.

1 What is WMI

See the Microsoft Official website for WMI for details. The simple explanation here is that the full name of WMI is Windows Management instrumentation, the Windows Management specification. It is the infrastructure for managing data and operations on Windows operating systems. We can use WMI scripts or apply automated management tasks.

From using WMI you can know that WMI supports the following languages:

Application Language Topic

Scripts written in Microsoft ActiveX script hosting, including Visual Basic Scripting Edition (VBScript) and Perl

Scripting API for WMI.

Start with Creating a WMI Script.

For script code examples, see WMI Tasks for Scripts and applications and the TechNet ScriptCenter script Repository.

Windows PowerShell

Getting Started with Windows PowerShell

WMI PowerShell Cmdlets, such as Get-wmiobject.

Visual Basic Applications

Scripting API for WMI.

Active Server Pages

Scripting API for WMI.

Start with Creating Active Server Pages for WMI.

C + + Applications

COM API for WMI.

Start with Creating a WMI application Using C + + and WMI C + + application Examples (contains Examples).

. NET Framework applications written in C #, Visual Basic. NET, or J #

Classes in the Microsoft.Management.Infrastructure namespace. (The system.management namespace is no longer supported). For more information, see WMI. NET Overview.

Unfortunately, WMI does not natively support python. But it doesn't matter, it supports VB, and two third-party libraries in Python, WMI and win32com, can be used in a similar VB-like usage. So next, let's talk about how to use it.

2 using WMI library to operate WMI with WMI2.1

The following is an example of all the services that traverse all processes:

Import= WMI. WMI ()#  traversal process  for in c.win32_process ():    Print  Process. ProcessId, process. Name#  traversal service  for in C.win32_service ():    Print service. ProcessId, service. Name

As you can see, it's very easy to use. But there are two problems: the WMI library is too slow, can you hurry up? The second is how to know the properties of the process and service in the example (such as ProcessID, etc.)? Because the WMI library is generating the underlying execution statements dynamically, using DIR (process) is not a way to get the ProcessID property.

For the first question, we can use the win32com library to solve it, which is much faster than WMI. And the second problem, first sell a Xiaoguanzi, after the article will be introduced.

2.2 Using the Win32com library to manipulate WMI

Win32com can imitate the behavior of VB, want to understand how to use win32com to operate WMI, the most direct way is to understand how to use VB to operate WMI. There are a number of examples available on Microsoft's website: WMI Tasks:processes, WMI tasks:services.

One example of this is the process:

StrComputer ="."SetobjWMIService =GetObject("winmgmts:"&"{impersonationlevel=impersonate}!\\"& StrComputer &"\root\cimv2")SetColprocesses = objWMIService.ExecQuery ("Select * from Win32_Process") for  eachObjprocessinchcolprocesses WScript.Echo"Process:"&objprocess.name Sngprocesstime= (CSng(objprocess.kernelmodetime) +CSng(objprocess.usermodetime))/10000000WScript.Echo"Processor Time:"&Sngprocesstime WScript.Echo"Process ID:"&Objprocess.processid WScript.Echo"working Set Size:"&Objprocess.workingsetsize WScript.Echo"Page File Size:"&Objprocess.pagefileusage WScript.Echo"Page faults:"&Objprocess.pagefaultsNext

It does this by first connecting to the namespace where the Win32_Process is located, and then executing the WQL statement (a SQL-like query statement) to find all the processes, and then print out the relevant information for each process. "GetObject" The specific use of WQL please see the official website, here is not detailed introduction.

So you can write with win32com (the properties printed in the example are not as numerous as they are for simplicity):

 from Import  = GetObject ('winmgmts:/root/cimv2')#  WMI = GetObject (' winmgmts: ') #更简单的写法processes = WMI. ExecQuery ('Select * from Win32_Process') processes:     Print (Process. ProcessID, process. Name)

It seems that the use of VB and win32com is very close! So when we want to use win32com to operate WMI, we can refer to the Microsoft Official website VB example, and then Bishi write the python version of the code.

In the example above, we used the query function ExecQuery to query for eligible content, but if we just want to get all the data, without a specific qualification, we can use the simpler way of--instancesof, then it can be written as follows:

 from Import  = GetObject ('winmgmts:/root/cimv2'= WMI. InstancesOf ('win32_process') for in processes:     Print (Process. ProcessID, process. Name)

Some readers may ask, how do we know what namespace we want to know, which instance we should get, and which properties in the instance to get?

3 WMI Namespace

Use the following script to get the namespace on the current computer:

 fromWin32com.clientImportGetObjectImportPywintypesdefenum_namespace (name):Try: WMI= GetObject ('winmgmts:/'+name) Namespaces= WMI. InstancesOf ('__namespace')         forNamespaceinchNamespaces:enum_namespace ('{Name}/{subname}'. Format (name=name, SubName=namespace. Name))exceptPywintypes.com_error:Print(Name,'Limit of authority')    Else:        Print(name) enum_namespace ('Root')

The content of the acquisition is probably like this. Indicates that some output was omitted):

Root
Root/subscription
root/subscription/ms_409
Root/default
root/default/ms_409
Root/cimv2
Root/cimv2/security
...
Root/cli
root/cli/ms_409
Root/security
...
Root/wmi
root/wmi/ms_409
Root/directory
Root/directory/ldap
root/directory/ldap/ms_409
Root/interop
root/interop/ms_409
Root/servicemodel
Root/securitycenter
Root/msapps12
Root/microsoft
...

A simple introduction to a common namespace:

Root is the highest level of the namespace hierarchy.

The CIMV2 namespace holds objects that are related to systems management domains, such as computers and their operating systems.

The default namespace holds a class that is created by defaults and does not specify a namespace.

Directory directory Service's common namespace, WMI creates a child namespace named LDAP.

SECURITY is used to support the namespace of WMI on a Windows 9x computer.

WMI uses the namespace of the Windows Driver Model providers class. This is to avoid conflicts with class names in the CIMV2 namespace.

Among them, root/cimv2 can be said to be the most basic and commonly used namespaces. Its role is mainly to provide information about computers, disks, peripherals, files, folders, file systems, network components, operating systems, printers, processes, security, services, shares, SAM users and groups, and more resources ; Manage Windows event logs such as read, Backup, Purge, copy, delete, monitor, rename, compress, decompress, and Change event log settings.

4 classes/instances and attributes/values

Knowing how namespaces are acquired, the main function of each namespace, how do you get the classes under a particular namespace, and their properties and values?

Windows provides a WMI tester that makes it particularly convenient to query these things. Press "Win+r" and enter WBEMTest to open the WMI Tester . The interface after opening is as follows:

Click "Connect", enter the namespace you want to query, and then click "Connect" to connect to a specific namespace.

Then click on "Enum Class", select "Recursive" in the popup screen, then click "OK", you will get all the classes under this namespace:

As you can see, the Win32_Process mentioned in the previous example is ranked among them, so we might as well double-click on it to see the specifics of it:

We can easily find the properties and methods of Win32_Process. In addition to using WBEMTest to view all classes under a particular namespace, we can also find all the classes in the Wmi/mi/omi providers. We click on this page in turn CIMWin32, Win32, Power Management events,win32 provider,operating System classes,win32_process finally found Win32_ Properties and methods of the process:

In contrast to the above two graphs, the methods are consistent.

So how do you get the instance and its value? We continue to click on the "instance" button on the right in the WBEMTest interface we just opened, and we'll show all the process instances. Double-click on a specific instance and then click on the "Show MOF" button on the right in the popup to display the value of the specific attribute in this instance.

Using the above methods of locating namespaces, classes, and attributes, we can happily use Python to play WMI.

5 combat, take IIS as an example

Having learned so much, let's take an object and practice practiced hand. Now that we have this requirement, we want to get the version number of IIS and all of its site names.

It is easier to find the description of IIS WMI on the Microsoft Official website, and according to our intuition, the information we are querying may be in a class containing setting in the class name, so it seems more likely to have iissetting (WMI), IIsWebServerSetting (WMI), IIsWebInfoSetting (WMI).

Take a look at each of these classes, and find an example in iissetting:

o = Getobj ("Winmgmts:/root/microsoftiisv2") Nodes= O.execquery ("SELECT * from iiswebserversetting where name= ' W3SVC/1 '") e=new Enumerator (nodes) for(;! e.atend (); E.movenext ()) {WScript.Echo (E.item (). Name+" ("+ E.item (). Path_. Class +")") } //The output should be:W3svc/1(iiswebserversetting) nodes= O.execquery ("SELECT * fromiissetting where name='W3SVC/1' ") E =new Enumerator (nodes) for(;! e.atend (); E.movenext ()) {WScript.Echo (E.item (). Name+" ("+ E.item (). Path_. Class +")") } //The output should be:W3svc/1(iisipsecuritysetting)W3SVC/1 (iiswebserversetting)

From this example, we can know that the IIS namespace is '/root/microsoftiisv2', and then we can query the various related classes directly in this space, such as "iiswebserversetting ”。

With WBEMTest and IIS Manager, we can see that the ServerComment attribute values in the iiswebserversetting instance are consistent with the site name:

The version information cannot be found in the class name containing the setting class, then go to the class name containing info in the class to see. Sure enough, the Majoriisversionnumber and Minoriisversionnumber properties were found in IIsWebInfo (WMI), respectively, for both large and small versions. Then we can easily write the following Python code to get the version and site name:

#Coding:utf-8 fromWin32com.clientImportGetobjectwmi= GetObject ('Winmgmts:/root/microsoftiisv2')#versionWebinfo = Wmi.execquery ('SELECT * from IIsWebInfo') [0]version='{Major}. {min}'. Format (major=Webinfo. Majoriisversionnumber, Min=Webinfo. Minoriisversionnumber)Print(version)#Site nameWebSettings = Wmi.execquery ('SELECT * from IIsWebServerSetting') Websites=' | '. Join (setting. ServerComment forSettinginchwebsettings)Print(websites)

6 Summary

Using Python to manipulate WMI, the biggest difficulty is not in how to write Python statements, but in what namespaces and corresponding classes and attributes you want to query. The content requires access to official documentation and exploration using WBEMTest. Once the necessary information has been obtained, it is very easy to write Python code.

Reprint Please specify source: http://www.cnblogs.com/dreamlofter/p/5846966.html

Use Python to play WMI

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.