Application of WMI in network programming

xiaoxiao2021-03-06  37

Application of WMI in network programming

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 C # Operation WMI. The class library used by WMI .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. The main function of the ConnectionOptions class ConnectionOptions is to provide all the settings required 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:

Attributes

Description

Authority

Gets or settings will be used to verify the right to specify the user

Locale

Get or sets the area settings that will be used to connect operations

Password

Provides passwords for WMI connection operations

Username

Provides username for WMI connection operations

The 2. ManagementScope class can create and remote computer (or local computers) of the WMI connection through the ManagementScope class, indicating that the management operable range. Creating a WMI connection can be used in two ways: (1) Using constructor, use the following constructor to initialize the managementScope class instance, and the WMI connection is established, as follows: Public ManagementScope (String Path, ConnectionOptions Options); where parameters Path represents the server and namespace of ManagementScope, Options contains ConnectionOptions for 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 the establishment of the ManagementScope instance, and is built on the WMI connection of the remote computer Majinhu: system.Management.ConnectionOptions conn = new connectionOptions (); conn.username = "WMI User Name"; conn.password = " Username corresponding password "; system.management.managementScope ms = new managementscope (" Majinhu // Root // CIMv2 ", CONN); (2) Take 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 password"; System.Management. ManagementScope MS = New ManagementScope ("Majinhu // Root // CIMv2"); ms.Options = conn; ms.connect (); 3. ObjectQuery class ObjectQuery class or its derived class for specifying queries 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 most common in the ObjectQuery class constructor, the specific syntax is as follows: Public ObjectQuery (String query); where the parameter Query represents the string of the query. 4. ManagementObjectSearcher Class ManagementObjectSearcher is mainly based on the specified query to retrieve a collection of WMI objects. 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 Properties of its Management ObjectSearcher class and its description: attribute

Description

Options

Options for searching for objects

Query

Inquiry called in the search

Scope

Find the range of objects

5. The ManagementObjectCollection class ManagementObjectCollection class is very simple, it mainly means that the different collections of the WMI instance include namespace, range, and query observation procedures. Creating the ManagementObjectCollection class has no constructor. 6. ManagementObject Class 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 their usual properties and methods:

Attribute or method

Description

Classpath

The path of the object of the object

Options

Other information to use when searching objects

Path

WMI path for object

Scope

This object is in which the range is stationary

Clone

Create a copy of the object

Copyto

Copy the object to another location

Delete

Delete object

Get

Bind to management objects

GetReled

Get a collection of objects related to this object (contact object)

GetReranceShipships

Get the collection of the association of this object

Invokemethod

Call the corresponding object method

PUT

Submit changes to the object

Second, WMI network applications - Get information about remote computers If you do 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, local machine pass and 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. Start the Visual Studio .NET first, select "File", "New", "Project" menu, set the "Project Type" to "Visual" in the "New Project" dialog box C # item, set "Template" 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 the "OK" button so that 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: use system.Management; used to reference the WMI operation class bit in the namespace located. 5. Switch the Visual Studio .NET Current window to the "Form1.cs" window, design the form. 6. Follow the table below to adjust the values ​​corresponding to each component attribute: component type

Component name

Attributes

Set the result

FORM

Form1

TEXT

Get remote computer hard drive information

Formborderstyle

Fixedsingle

MaximizeBox

False

Textbox

TextBox3

Passwordchar

*

Button

Button1

Flatstyle

Flat

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 the remote computer, extract the query to get the data and display: private void button1_click (object sender, system.eventargs e) {long MB = 1048576; // 1024x1024 // Set the generated WMI required All Settings System.Management.ConnectionOptions Conn = New ConnectionOptions (); conn.usename = textBox2.text; // User name Conn.Password = textBox3.text; // password // Settings for performing WMI operation range SYSTEM .Management.managementscope ms = new managementscope ("" TEXTBOX1.TEXT "// root // CIMv2", conn; try {// Connect to the actual WMI range ms.connect (); // setting pass SUMMARY ObjectQuery query WMI to query = new ObjectQuery ( "select FreeSpace, Size, Name from Win32_LogicalDisk where DriveType = 3"); // WQL statement, WMI WMI query and set the operating range, retrieve object set ManagementObjectSearcher Searcher WMI = New ManagementObjectSearcher (MS, Query); // Asynchronous call WMI query management = searcher.get (); double free = 0; double us = 0; Double Total = 0; listbox1.items.clear (); // Pass Retrieve the generated example collection of WMI to obtain the hard disk information, forward (ManagementObject Return IN ReturnCollection) {listbox1.items.add ("Disk Name:" Return ["Name"]. TOSTRING ()); free = convert.toint64 (R ETURN ["Free"]) / MB; // Get the available space for the hard disk USE = (convert.Toint 64 (Return [""]) - Convert.Toint64 (Return ["FREESPACE"]) / MB; // Get The hard disk has been used to obtain the total space of the hard disk Total = Convert.Toint64 (Return ["" "]) / MB; listbox1.items.add (" Total: " Total.toTRING () " MB "); ListBox1.items.Add ("Used Space:" Use.toTString () "MB"); ListBox1.Items.Add ("Available Space:" Free.toTString () "MB");}} catch (Exception EE) {MessageBox.show ("Connect" TextBox1.text "error, error message is:"

Ee.Message, "Errors!");}} 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, the two WMI network applications - 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 step of using the WMI control remote computer: 1. First start Visual Studio .NET, select "File", "New", "Project" menu, pop up "New Project" dialog box "project Type "Set to" Visual C # item ", set" Template "to" Windows Applications ", enter" Using WMI Control Remote Computer "in the Name text box, enter" E: E: /VS.NET Project, and then click the "OK" button so that the 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 as shown in Figure 3: 4. Adjust the value corresponding to each component attribute according to the data below: Component Type

Component name

Attributes

Set the result

FORM

Form1

TEXT

Using WMI to control remote computers

Formborderstyle

Fixedsingle

MaximizeBox

False

Textbox

TextBox3

Passwordchar

*

Button

Button1

Flatstyle

Flat

ComboBox

ComboBox1

Items

Restart remote shutdown

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

New Post(0)