远程操作服务器的Windows服务和进程

4 篇文章 0 订阅
3 篇文章 0 订阅

WMI 简介

Windows Management Instrumentation (WMI)是可伸缩的系统管理结构,该规范采用一个统一、基于标准且可扩展的面向对象接口。它提供与系统管理员信息和基础WMI API交互的标准方法,主要由系统管理应用程序开发人员和系统管理员用来访问和操作系统管理信息;它可用来生成组织和管理系统信息的工具,使系统管理人员能够更密切的监视系统活动。

WMI提供了一套内置在Microsoft Windows操作系统中的丰富的系统管理服务,可以在有大量的应用程序、服务和设备的系统中提供全方位的管理功能。它允许应用程序的开发者,使用简单的、一致的机制,去查询企业中的任一台计算机上的信息,或是进行系统配置。

通过WMI接口可以获得的信息量是惊人的,包括硬件设置,状态信息,驱动器配置,BIOS信息,应用程序的设置,事件记录信息,以及其他。WMI通过一组API来获得信息,但它表征的是一种通过一个简单,工业标准对象管理模式来获取信息的函数。这使得应用程序的开发者不必学习Windows的每一个API的具体细节。

.Net Framework SDK对WMI提供了全面的支持,.Net Framework SDK为Visual C#能够操作WMI提供了一个专门的命名空间"System. Management"。在命名空间"System. Management"中提供了大量用以处理和WMI相关的类、接口和枚举。在使用WMI之前,必须在工程中添加对System.Management.dll的引用,然后声明using System. Management;

WMI API(Windows服务)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace Siemens.Protocol.QuartzScheduler
{
    /*"Stopped","Start Pending","Stop Pending","Running","Continue Pending","Pause Pending","Paused","Unknown"*/
    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 && userName.Length > 0)
            {
                ConnectionOptions connectionOptions = new ConnectionOptions();
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
                ManagementScope managementScope = new ManagementScope("\\\\" + host + "\\root\\cimv2", connectionOptions);
                this.managementClass.Scope = managementScope;
            }
        }
        // 验证是否能连接到远程计算机
        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;
        }
        // 获取指定服务属性的值
        public object GetServiceValue(string serviceName, string propertyName)
        {
            ManagementObject mo = this.managementClass.CreateInstance();
            mo.Path = new ManagementPath(this.strPath + ".Name=\"" + serviceName + "\"");
            return mo[propertyName];
        }
        // 获取所连接的计算机的所有服务数据
        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;
        }
        // 获取所连接的计算机的指定服务数据
        public string[,] GetServiceList(string serverName)
        {
            return GetServiceList(new string[] { serverName });
        }
        // 获取所连接的计算机的的指定服务数据
        public string[,] GetServiceList(string[] serverNames)
        {
            string[,] services = new string[serverNames.Length, 4];
            ManagementObject mo = this.managementClass.CreateInstance();
            for (int i = 0; i < serverNames.Length; 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;
        }
        // 启动指定的服务
        public string StartService(string serviceName)
        {
            string strRst = null;
            ManagementObject mo = this.managementClass.CreateInstance();
            mo.Path = new ManagementPath(this.strPath + ".Name=\"" + serviceName + "\"");
            try
            {
                if ((string)mo["State"] == "Stopped")//!(bool)mo["AcceptStop"]
                    mo.InvokeMethod("StartService", null);
            }
            catch (ManagementException e)
            {
                strRst = e.Message;
            }
            return strRst;
        }
        // 暂停指定的服务
        public string PauseService(string serviceName)
        {
            string strRst = null;
            ManagementObject mo = this.managementClass.CreateInstance();
            mo.Path = new ManagementPath(this.strPath + ".Name=\"" + serviceName + "\"");
            try
            {
                //判断是否可以暂停
                if ((bool)mo["acceptPause"] && (string)mo["State"] == "Running")
                    mo.InvokeMethod("PauseService", null);
            }
            catch (ManagementException e)
            {
                strRst = e.Message;
            }
            return strRst;
        }
        // 恢复指定的服务
        public string ResumeService(string serviceName)
        {
            string strRst = null;
            ManagementObject mo = this.managementClass.CreateInstance();
            mo.Path = new ManagementPath(this.strPath + ".Name=\"" + serviceName + "\"");
            try
            {
                //判断是否可以恢复
                if ((bool)mo["acceptPause"] && (string)mo["State"] == "Paused")
                    mo.InvokeMethod("ResumeService", null);
            }
            catch (ManagementException e)
            {
                strRst = e.Message;
            }
            return strRst;
        }
        // 停止指定的服务
        public string StopService(string serviceName)
        {
            string strRst = null;
            ManagementObject mo = this.managementClass.CreateInstance();
            mo.Path = new ManagementPath(this.strPath + ".Name=\"" + serviceName + "\"");
            try
            {
                //判断是否可以停止
                if ((bool)mo["AcceptStop"])//(string)mo["State"]=="Running"
                    mo.InvokeMethod("StopService", null);
            }
            catch (ManagementException e)
            {
                strRst = e.Message;
            }
            return strRst;
        }
    }
}

WMI API(进程)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace Siemens.Protocol.QuartzScheduler
{
    public class Win32ProcessManager
    {
        private string strPath;
        private ManagementClass managementClass;
        public Win32ProcessManager() : this(".", null, null)
        {
        }
        public Win32ProcessManager(string host, string userName, string password)
        {
            this.strPath = "\\\\" + host + "\\root\\cimv2:Win32_Process";
            this.managementClass = new ManagementClass(strPath);
            if (userName != null && userName.Length > 0)
            {
                ConnectionOptions connectionOptions = new ConnectionOptions();
                connectionOptions.Username = userName;
                connectionOptions.Password = password;
                ManagementScope managementScope = new ManagementScope("\\\\" + host + "\\root\\cimv2", connectionOptions);
                this.managementClass.Scope = managementScope;
            }
        }

        // 停止指定的服务
        public string KillService(string serviceName)
        {
            ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_Process");
            ManagementObjectSearcher link = new ManagementObjectSearcher(managementClass.Scope, oq);
            ManagementObjectCollection Collection = link.Get();
            foreach (ManagementObject Process in Collection)
            {
                if (Convert.ToString(Process["Name"]) == serviceName)
                {
                    string[] Tparas = { "1" };
                    Process.InvokeMethod("Terminate", Tparas);
                }
            }
            return "";
        }
    }
}

希望对你能够提供帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值