Use the C # to control the service of remote computers

xiaoxiao2021-03-06  48

Some classes are provided in .NET to display and control the services on the Windows system, you can implement access to the remote computer service service, such as the serviceController class under the System.ServiceProcess Namespace, some WMI operations below System.Management . Although it can be easily controlled by ServiceController, it is very intuitive, simple and easy to understand. But I think that his functionality is a single single, and it may be a bit a single, and the operation of multiple services may be more troublesome, and the specific data of all services in the system cannot be listed. What you want to talk about is how to use the System.Management component to operate the services on the remote and local computers.

As part of the Windows 2000 operating system, WMI provides a scalable, scalable management architecture. Public Information Model (CIM) is an extensible, object-oriented architecture designed by the Distributed Management Task Standards Association (DMTF), For management systems, networks, applications, databases, and devices. The Windows management specification is also known as Cim for Windows, providing unified access to management information. If you need to get a detailed WMI message, please check the MSDN. The System.Management component provides access to a large number of management information and management events, which are related to the system, devices, and application settings of the system, device, and application in accordance with the Windows Management Specification (WMI) structure.

But the above is not our most concerned, the following is the topic we need to talk.

There is no doubt that we have to reference the System.Management.dll assembly and use the class under the system.management namespace, such as managementClass, ManagementObject, etc. The following is packaged with a class named Win32ServiceManager, and the code is as follows:

Using system;

Using system.management;

Namespace zz.wmi

{

Public Class Win32ServiceManager

{

PRIVATE STRING STRPATH;

Private managementClass ManagementClass;

Public Win32ServiceManager (): this ("." NULL, NULL)

{

}

Public Win32ServiceManager (String Host, String UserName, String Password)

{

THIS.STRPATH = " Host " // root // CIMv2: Win32_Service ";

This.ManagementClass = New ManagementClass (STRPATH);

IF (username! = null && usrname.length> 0)

{

ConnectionOptions ConnectionOptions = New ConnectionOptions ();

ConnectionOptions.userName = Username;

ConnectionOptions.password = password;

Managementscope managementscope = new managementscope ("" Host "// root // CIMv2", ConnectionOptions;

This.ManagementClass.scope = managementscope;

}

}

// Verify that it can be connected to the remote computer public static bool RemoteConnectValidate (String Host, String Username, String Password)

{

ConnectionOptions ConnectionOptions = New ConnectionOptions ();

ConnectionOptions.userName = Username;

ConnectionOptions.password = password;

Managementscope managementscope = new managementscope ("" Host "// root // CIMv2", ConnectionOptions;

Try

{

Managementscope.connect ();

}

Catch

{

}

Return managementscope.isconnected;

}

/ / Get the value of the specified service properties

Public Object GetServiceValue (String ServiceName, String PropertyName)

{

ManagementObject mo = this.managementClass.createInstance ();

mo.path = new managementPath (this.strpath ". Name = /" " service");

Return Mo [PropertyName];

}

/ / Get all service data of the connected computer

Public String [,] getServiceList ()

{

String [,] Services = new string [this.managementclass.getinstances (). count, 4];

INT i = 0;

Foreach (ManagementObject Mo in this.ManagementClass.GetInstances ())

{

Services [i, 0] = (string) Mo ["name"];

Services [i, 1] = (string) Mo ["DisplayName"];

Services [i, 2] = (string) Mo ["state"];

Services [i, 3] = (string) Mo ["startmode"];

i ;

}

Return Services;

}

/ / Get the specified service data of the connected computer

Public String [,] getServiceList (String Servername)

{

Return GetServiceList (new string [} {servername});

}

/ / Get the specified service data of the connected computer

Public string [,] getServiceList (String [] ServerNames)

{

String [,] Services = new string [servernames.length, 4];

ManagementObject mo = this.managementClass.createInstance ();

For (int i = 0; i

{

Mo.path = new managementPath (this.strpath ". name = /" " serverNames [i] " / ""); services [i, 0] = (string) Mo ["name"];

Services [i, 1] = (string) Mo ["DisplayName"];

Services [i, 2] = (string) Mo ["state"];

Services [i, 3] = (string) Mo ["startmode"];

}

Return Services;

}

// Stop the specified service

Public String StartService (String ServiceName)

{

Stringst = NULL;

ManagementObject mo = this.managementClass.createInstance ();

mo.path = new managementPath (this.strpath ". Name = /" " service");

Try

{

IF (String) Mo ["State"] == "stopped") ///! (bool) mo ["acceptstop"]

Mo.invokeMethod ("StartService", NULL;

}

Catch (ManagementException E)

{

Strrst = E.MESSAGE;

}

Return strrs;

}

// Pause the designated service

Public String PauseService (String ServiceName)

{

Stringst = NULL;

ManagementObject mo = this.managementClass.createInstance ();

mo.path = new managementPath (this.strpath ". Name = /" " service");

Try

{

/ / Judgment Can I suspend?

IF ((Bool) Mo ["AcceptPause"] && (String) Mo ["State"] == "Running")

Mo.invokeMethod ("Pauseservice", NULL;

}

Catch (ManagementException E)

{

Strrst = E.MESSAGE;

}

Return strrs;

}

// Restore the specified service

Public String ResumeService (String ServiceName)

{

Stringst = NULL;

ManagementObject mo = this.managementClass.createInstance ();

mo.path = new managementPath (this.strpath ". Name = /" " service");

Try

{

// Judgment can be recovered

IF ((BOOL) Mo ["AcceptPause"] && (String) Mo ["State"] == "paused") Mo.invokeMethod ("resuMeservice", null;

}

Catch (ManagementException E)

{

Strrst = E.MESSAGE;

}

Return strrs;

}

// Stop the specified service

Public String StopService (String ServiceName)

{

Stringst = NULL;

ManagementObject mo = this.managementClass.createInstance ();

mo.path = new managementPath (this.strpath ". Name = /" " service");

Try

{

/ / Determine if it can stop

IF ((bool) mo ["acceptstop"]) // (String) Mo ["state"] == "running"

Mo.invokeMethod ("StopService", NULL);

}

Catch (ManagementException E)

{

Strrst = E.MESSAGE;

}

Return strrs;

}

}

}

Test the success of the connection in Win32ServiceManager through RemoteConnectValidate; additionally provides the GetServiceValue method and GetServiceList method and its overload to obtain service information; the four methods behind are controlled the status of the service.

The following is a simple window to use it.

The rough interface is as follows:

The above form can be made soon via VS.NET 2003, and some add-on code is listed below:

Using zz.wmi;

Namespace ZZFORM

{

Public Class Form1: System.Windows.Forms.form

{

// ......

Private Win32ServiceManager ServiceManager;

Public Form1 ()

{

InitializationComponent ();

THIS.ServiceManager = NULL;

}

// ......

[Stathread]

Static void main ()

{

Application.run (New Form1 ());

}

// Modify the service status

Private Void ButtonChangeState_Click (Object Sender, System.EventArgs E)

{

Switch ((Button Sender) .Text)

{

Case "start":

String Startrst = this.serviceManager.StartService (this.listviewService.selectedItems [0] .SUBITEMS [0] .text);

IF (StartRST == NULL)

Messagebox.show ("Successful operation, please click to get the refresh button to refresh the result!");

Else

Messagebox.show (StartRST);

Break;

Case "Pause":

String Startpause = this.serviceManager.pauseservice (this.listviewservice.selecteditems [0] .SUBITEMS [0] .text); if (startpause == null)

Messagebox.show ("Successful operation, please click to get the refresh button to refresh the result!");

Else

Messagebox.show (Startpause);

Break;

Case "Continue":

String StartResume = this.serviceManager.ResuMeservice (this.listviewservice.selectedItems [0] .SUBITEMS [0] .text);

IF (StartResume == Null)

Messagebox.show ("Successful operation, please click to get the refresh button to refresh the result!");

Else

MessageBox.show (StartResume);

Break;

Case "Stop":

String StartStop = this.serviceManager.StopService (this.listviewService.selectedItems [0] .SUBITEMS [0] .text);

IF (StartStop == NULL)

Messagebox.show ("Successful operation, please click to get the refresh button to refresh the result!");

Else

Messagebox.show; STARTSTOP

Break;

}

}

// Get and refresh data

Private Void ButtonLoadRefresh_Click (Object Sender, System.EventArgs E)

{

IF (THIS.TEXTBOXHOST.TEXT.TRIM (). LENGTH> 0)

{

IF (THIS.TEXTBOXHOST.TEXT.TRIM () == ")

{

THIS.ServiceManager = new win32servicemanager ();

}

Else

{

IF (Win32ServiceManager.RemoteconnectValidate (this.TextBoxHost.Text.trim (), this.TextBoxName.Text.trim (), this.TextBoxPassword.Text.trim ()))

{

This.serviceManager = new Win32ServiceManager (this.TextBoxHost.Text.trim (), this.TextBoxName.Text.trim (), this.TextBoxPassword.Text.trim ());

}

Else

{

MessageBox.show ("Connect to Remote Computer Verification Error.");

Return;

}

}

String [,] Services = serviceManager.getServiceList ();

This.listviewService.beginupdate ();

THISTVIEWSERVICE.ITEMS.CLEAR ();

For (int i = 0; i

{

ListViewItem item = new listviewitem (new string [] {services [i, 0], services [i, 1], services [i, 2], services [i, 3]});

This.listviewService.Items.Add (item);

}

This.listviewService.Endupdate ();

Else

MessageBox.show ("Please enter your computer name or IP address");

}

}

}

Explanation, in fact, the properties and methods of a service are much more, we can list all the properties and methods by instantiation managementClass class, using its Properties property and the Methods property. Each service instance generated in the Win32ServiceManager above is a managementOBejct type. In fact, there is a strong type of class that can be generated by programming and tools.

Summary, by reference the System.Management namespace, the above is simple to display and operate over the access / root / cimv2: win32_service namespace. In addition, we can also access some of the hardware information, software information, and networks of the computer by accessing other namespaces, and interested readers can study.

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

New Post(0)