Application of WMI in network programming

xiaoxiao2021-03-06  58

WMI is a referred to as Windows Management Instrument, namely "Window Management Specification". As early as Windows NT4.0, WMI has already begun, but the WMI core component does not release with NT4.0, if you want to support WMI in NT4.0, you need to install the core component of WMI, you can be in VS The "WMI" directory in the fifth sheet in the .NET Enterprise builds it. Installing the WMI core component in NT4.0, you must ensure that the NT 4.0 version is a service pack 4.0 or an updated version. If your machine is used by Windows 2000 or later, then it is not so troublesome, because WMI is installed by default.

WMI's function is very powerful. It can achieve a lot of work that is considered difficult by WMI, and it is also a good supplement to .NET Framework SDK, especially in the current, .NET Framework SDK function is not very complete, effective The use of WMI can indeed simplify a lot of difficulties.

Using WMI can not only solve many of the local machines, but also to write network applications, such as obtaining various data information of remote computers through WMI, controlling various behaviors of remote computers, and this is as convenient as operating locally. . And this is only a prerequisite, that is, you must know the superuser and corresponding password of the remote computer.

I. Introduction to the class library for WMI use in C #

The .NET Framework SDK provides comprehensive support for WMI, .NET Framework SDK is C # can operate WMI to provide a special namespace System.Management. A large number of classes, interfaces, and enumerations associated with WMI are provided in the namespace System.Management.

The members in System.Management in the namespace are very complicated. Because the space limit is fully introduced, it is not possible. According to my experience, I don't think I have to understand and master the use of WMI in C #. The following six classes should be the focus of learning, respectively, respective, management, managementObjectSearcher, ManagementObject-Collection, and ManagementObject. Let's briefly introduce six classes.

1.ConnectionOptions class

The main function of the ConnectionOptions class is to provide all the required settings for the established WMI connection. When operating the remote computer with WMI, the WMI connection is first performed, and the WMI connection is mainly used by the ManagementScope class, and the WMI connection to successfully complete the remote computer WMI username and password. The ConnectionOptions class can provide this information through its properties. The following table is some of the main properties of the ConnectionOptions class and its simple instructions:

Property Description Authority Gets or Settings Locale for verifying the Specify User Locale Gets or settings to set the area settings for connection operations Password provides passwords for WMI connection operations UserName Provides username for WMI connection operations

2.ManagementScope class

The WMI connection of the remote computer (or local computer) can be established via the ManagementScope class, indicating that the management operable range. Create a WMI connection can pass two methods:

(1) Use the constructor to initialize the ManagementScope class instance using the following constructor, and the WMI connection is established, as follows:

Public ManagementScope

String path,

ConnectionOptions Options

);

Where parameter Path represents the server and namespace of ManagementScope, Options contains ConnectionOptions about the options for the connection. The use of the constructor is risky because if the WMI connection is not established according to the options provided, the program will throw an exception. The following code uses this constructor to build a build managementScope instance and is built on the WMI connection of remote computer Majinhu:

System.Management.ConnectionOptions conn = new connectionOptions ();

Conn.username = "WMI User Name";

Conn.password = "This username corresponds to the password";

System.Management.ManagementScope MS = New ManagementScope ("Majinhu // Root // Cimv2", CONN);

(2) Use the Connect method provided in ManagementsCope. Members in ManagementScope are very few, most common methods and properties: common attributes are options, mainly providing parameters for WMI; common method is Connect, which can be built from the WMI connection of remote computers. The following is a specific code for establishing a WMI connection using the Connect method:

System.Management.ConnectionOptions conn = new connectionOptions ();

Conn.username = "WMI User Name";

Conn.password = "This username corresponds to the password";

System.Management.ManagementScope MS = New ManagementScope ("Majinhu // Root // CIMv2");

Ms.Options = conn;

Ms.Connect ();

3. ObjectQuery class

ObjectQuery class or its derived class is used to specify a query in Management ObjectSearcher. The query string is generally used to construct the ObjectQuery instance. The query string is a WQL language similar to the SQL language. The following ObjectQuery class constructor is the most common, the specific syntax is as follows:

Public ObjectQuery (String Query);

Where parameter Query represents the string of queries.

4.ManagementObjectSearcher class

ManagementObjectSearcher is mainly to retrieve a collection of WMI objects based on the specified query. ManagementObjectSearcher is also very simple, and its GET method is very important, and Management ObjectSearcher performs WMI queries through the GET method and collects the result. The return value of the GET method is an instance of the ManagementObjectCollection that contains the object that matches the specified query. The following table is the common attribute of its Management ObjectSearcher class and its description:

Property Description Options About How to Search Objects Query Calls in the search SCOPE to find the range of objects

5.ManagementObjectCollection class

The ManagementObjectCollection class is very simple, it mainly indicates that the different collections of the WMI instance are included in the namespace, range, and query observation procedures. Creating the ManagementObjectCollection class has no constructor.

6.ManagementObject Class

The ManagementObject class is a single management object or class. The objects corresponding to the managementObject can be invoked by the method in the managementObject, thereby performing the corresponding operation. The ManagementObject class is a rich class. Below is a list of its usual properties and methods: Properties or Method Description ClassPath Objects The path of ClassPath objects Options Search Other information to use the other information of other information to use the WMI path of the other information of the PATH object, SCOPE Scope Clone Creating a copy of the object CopyTo Copy the object to another Delete Delete object GET Bind to the management object getReled Get GetReletionShips related to the object (Contact Object) GetReranceShips Get the associated collection of the association of this object Call correspondence Object Method PUT Submit Change to Objects Second, WMI Network Application - Get Information about Remote Computers

If WMI does not use WMI, you want to get system data for remote computers, the most common method is to run a client program on a remote computer, locally passing and using this client program to get system data for remote computers. This implementation method is that the programming or the post-distribution is difficult. And WMI, everything is very simple. This example is described below, its function is to obtain remote computer hard disk data using WMI. You can get other data for remote computers just a slight modification of this program. The following is a specific implementation step:

1. First start the Visual Studio .NET, select "File", "New", "Project" menu, and set the Project Type to "Visual C # Item" and will "Template in" New Project "dialog box. "Set to" Windows Application ", enter" Get Remote Computer Hard Disk Information "in the Name text box, enter" E: /VS.NET Project "in the" Location "text box, then click OK Button, so the project is established.

2. Because the Visual Studio .NET default compilation environment does not include a container file system.management.dll, named space System.Management.dll, so first introduces this DLL file in the project file. First select "References" in the Solution Explorer, then right-click, in the pop-up menu, select Add Reference, Select ".NET" page in the "Add Reference" dialog box. After selecting "System.Managemen" in the Component Name column, click the "Select" button. At this point, "System.Managemen" is added in the "Selected Component" field, and then click the "OK" button, now the Visual Studio .NET integrates the development environment to import namespace System.Managemen.

3. In the Solution Explorer window, double-click the Form1.cs file to enter the editing interface of the Form1.cs file.

4. At the beginning of the Form1.cs file, add it after the default naming namespace of the system:

Using system.management;

Used to reference the namespace located in the WMI operation class.

5. Switch the Visual Studio .NET Current window to the "Form1.cs" window, design the form.

6. Follow the tables to adjust the values ​​corresponding to each component attribute:

Component Type Component Name Property Settings Formform1Text Get Remote Computer Hard Disk Information FormolderstylefixedSingle MaximizeBoxFalseTextBoxTextBox3PasswordChar * ButtonButton1FlatstyleFlat

7. Switch the current window of Visual Studio .Net to the editing window of the Form1.cs file, and replace the processing code corresponding to the Click event of Button1 in Form1.cs with the following code. The role of the following code is to perform WMI queries for remote computers, extract queries to get data and display results: private void button1_click (Object Sender, System.Eventargs E)

{

Long MB = 1048576; // 1024x1024

// Set all the settings required for the generated WMI

System.Management.ConnectionOptions conn = new connectionOptions ();

Conn.username = textbox2.text; // Username

Conn.password = TextBox3.text; // password

/ / Set the range used to perform WMI operations

System.Management.ManagementScope MS = New ManagementScope (" TextBox1.text " // Root // CIMv2 ", CONN);

Try

{

// Connect to the actual WMI range

Ms.Connect ();

/ / Set the content to be queried by WMI

ObjectQuery Query = New ObjectQuery ("SELECT FREESPACE, SIZE, NAME FROM WIN32_LOGICALDISK WHERE DRIVETYPE = 3");

/ / WQL statement, set WMI query content and WMI operation range, retrieve WMI object collection

ManagementObjectSearcher Searcher = New ManagementObjectSearcher (MS, Query);

// Asynchronous call WMI query

ManagementObjectCollection ReturnCollection = Searcher.get ();

Double free = 0;

Double USE = 0;

Double total = 0;

Listbox1.items.clear ();

// Retrieve the hard disk information by retrieving the example collection of the generated WMI

FOREACH (ManagementObject Return In ReturnCollection)

{

Listbox1.items.add ("Disk Name:" Return ["Name"]. TOSTRING ());

Free = convert.Toint64 (Return ["FreeSpace"]) / MB; // Get the available space for your hard drive

Use = (convert.Toint 64 (Return ["Size"]) - Convert.Toint64 (Return ["FreeSpace"]) / MB; // Get the used space for your hard drive

/ / Get the total space of the hard disk

Total = Convert.Toint 64 (Return ["Size"]) / MB;

Listbox1.items.add ("Total:" Total.toTString () "MB");

ListBox1.Items.Add ("Use Space:" Use.toTString () "MB");

Listbox1.items.add ("Available Space:" Free.toTString () "MB");

}

Catch (Exception EE)

{

Messagebox.show ("Connection" TextBox1.text "error, error message is:" EE.MESSAGE, "Error!");

}

}

8. Press the shortcut key F5 to run the program. After entering the IP address or user name, super user name, and password of the remote computer correctly, click the "Get Hard Disk Information" button, the program will get the data of the hard disk of the specified computer and display it.

How, does it have a feeling of hackers? Here's the use of WMI to complete a more "cool" program - restart or turn off the remote computer!

Third, WMI network application 2 - control remote computer

WMI can not only get the desired computer data, but also to remotely control. Remote control computers are not only a dream of hackers, but also to most network managers, especially in modern networks, the local area network faced by each network manager is composed of a huge computer group, If each computer of a valid management network is very important. Currently, network management software is the usual practice to run client programs on remote computers, running a control program on a local computer, and implements remote control of your computer through this two program direct communication. The disadvantage of this approach is very obvious. This remote management cannot be implemented when the client closes the background program.

In fact, the remote control software, WMI is a good choice, especially in Windows 2000, XP has become the mainstream operating system, using WMI writing remote control software, I can omit the most headache of remote control software - distribution Client program.

The remote control program described in this section allows the user to restart and close the remote computer. Below is the specific implementation steps of using the WMI control remote computer in C #:

1. First start the Visual Studio .NET, select "File", "New", "Project" menu, and set the Project Type to "Visual C # Item" and will "Template in" New Project "dialog box. "Set to" Windows Application ", enter" Name "text box Enter" WMI Control Remote Computer ", enter" E: /VS.NET Project "in the" Location "text box, and then click OK Buttons, this project is established.

2. Repeat the "Get Remote Computer Hard Disk Information" items in the second to fourth steps.

3. Switch the Visual Studio .NET Current window to the "Form1.cs" window, follow the Form Design by Figure 3:

4. Adjust the value corresponding to each component attribute as follows:

Component Type Component Name property results FormForm1Text control the remote computer using WMI FormBorderStyleFixedSingle MaximizeBoxFalseTextBoxtextBox3PasswordChar * Buttonbutton1FlatStyleFlatComboBoxcomboBox1Items restart the remote shutdown 5. Visual Studio .Net current window switches to the Form1.cs file edit window, and replaced with the following code in Form1.cs Button1's Click event corresponds to processing code. The role of the following code is to perform a corresponding remote control of the remote computer according to the user's selection:

Private void Button1_Click (Object Sender, System.Eventargs E)

{

/ / Determine the range of WMI operations

ConnectionOptions Options = New ConnectionOptions (); options.username = textbox2.text; // User Name

Options.password = textbox3.text; // User password

Try

{

Managementscope conn = new managementscope (" TEXTBOX1.TEXT " // root // CIMv2 ", Options;

CONN.CONNECT ();

/ / Determine the content of the WMI operation

ObjectQuery oq = New ObjectQuery ("SELECT * FROM WIN32_OPERATISTYSYSTEM");

ManagementObjectSearcher Query1 = New ManagementObjectSearcher (CONN, OQ);

/ / Get WMI operation content

ManagementObjectCollection QueryCollection1 = query1.get ();

/ / According to the user selection to perform the corresponding remote operation

FOREACH (ManagementObject Mo in QueryCollection1)

{

String [] ss = {"};

IF (ComboBoX1.Text == "Restart")

Mo.invokeMethod ("reboot", ss); // perform reboot operation

Else IF (ComboBoX1.Text == "Remote Shutdown")

Mo.invokeMethod ("Shutdown", SS); // Execute Remote Shutdown

Else

Messagebox.show ("Select Incorrect Operation!", "Error!");

}

}

Catch (Exception EE)

{

Messagebox.show ("Connect" TextBox1.text "error, error message is:" EE.MESSAGE); // report error

}

}

6. Press F5 shortcut to run the program. Enter the remote computer name or IP address you want to control in the "Computer Name or IP Address" text box, enter the account and password with WMI operation in "User Name" and "Password" text boxes with WMI permissions. After selecting the control type of the remote computer, click the "Execute" button, and the program can be controlled accordingly for the specified remote computer.

Fourth, summary

Through the above two examples, it can be seen that WMI is indeed a very useful thing, but because it is still new, there is no complete introduction to the domestic and even abroad, the above is just a browsing of the browsing, in fact, there are many WMIs. Function also requires constant exploration, I hope that the content of this chapter can understand everyone, master WMI's use method helps.

Source program download address:

Http://www.cfan.com.cn/qikan/cfan/source/0308csh.zip.

转载请注明原文地址:https://www.9cbs.com/read-116832.html

New Post(0)