static void Main(string[] args)
{
ConnectionOptions op = new ConnectionOptions();
// 登陆远程计算机的远程,
op.Username = "Domain\\Domainuser";
op.Password = "password";
// 该处不能使用ip必须是"计算机名称.域名\root\cimv2"
ManagementScope scope = new ManagementScope(@"\\Servername.Domain\root\cimv2", op);
scope.Connect();
ManagementPath path = new ManagementPath("Win32_Service");
using(ManagementClass services = new ManagementClass(scope, path, null))
{
foreach (ManagementObject service in services.GetInstances())
{
Console.WriteLine("{0}:{1}",service.GetPropertyValue("Name").ToString(),service.GetPropertyValue("State").ToString());
}
} Console.ReadKey();
}

如何远程Stop/Start远程机子上的服务?

在gfsoso上搜出别人总结的经验: http://www.gkspk.com/view/programming/working-with-windows-services-using-csharp-and-wmi/

远程控制可以有以下几种方式:

  • WMI Queries via classes in the System.Management namespace,
  • Strongly-typed WMI proxy classes generated using MgmtClassGen.exe, and
  • The System.ServiceProcess.ServiceController class.

WMI queries

首先我们需要使用ConnectionOptions来连通远程机:

 ConnectionOptions options = new ConnectionOptions();

 // If we are connecting to a remote host and want to
// connect as a different user, we need to set some options
//options.Username =
//options.Password =
//options.Authority =
//options.EnablePrivileges = // If we are connecting to a remote host, we need to specify the hostname:
//string providerPath = @"\\Hostname\root\CIMv2";
string providerPath = @"root\CIMv2"; ManagementScope scope = new ManagementScope(providerPath, options);
scope.Connect();

我们使用WMI支持一种查询方式叫做WQL,它的用法是类似于SQL。我们可以使用WQL去查询某台服务器的上的服务运行状态:

ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Service WHERE Name LIKE 'SQL%'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); foreach (ManagementObject o in searcher.Get())
{
string name = o["Name"];
...
}

我们可以使用ManagementObject去对单个远程的WindowsService进行控制:比如停止服务(Invoke函数:StopService)或者启动服务(Invoke 函数:StartService);

 ManagementPath path = new ManagementPath("Win32_Service.Name='SomeWindowsService'");
ManagementObject obj = new ManagementObject(scope, path, new ObjectGetOptions());
ManagementBaseObject outParams = obj.InvokeMethod("StartService", (ManagementBaseObject)null, null);
uint returnCode = System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);

上边这种方法是一种同步的方法,当然我们也可以使用异步接收InvokeMethod执行结果。

 ManagementOperationObserver observer = new ManagementOperationObserver();
// The ObjectReadyHandler method will need a prototype of
// public void ObjectReadyHandler(object sender, ObjectReadyEventArgs e) { ... }
observer.ObjectReady += ObjectReadyHandler;
obj.InvokeMethod(observer, "StartService", new object[]);

ManagementOperationObserver有两个事件可以订约,你可以订约ObjectReady,也可以订约Completed事件。

WMI proxy classes

你可以使用.NET Framework包含的一个强类型WMI代理类生成工具,你可以是使用一下命令生成对类Win32_Service的代理类:

MgmtClassGen.exe Win32_Service /L CS /O some.namespace /N root\cimv2 /P ServiceProxy.cs

执行这些代码后,你将得到一个ServiceProxy.cs文件,在使用该代理类的时候,你还需要结合ConnectionOptions使用:

 string condition = "Name LIKE 'SQL%'";
ServiceProxy.ServiceCollection sc = ServiceProxy.GetInstances(scope, condition);
foreach (ServiceProxy s in sc)
{
string name = s.Name;
...
s.StartService();
}

Service Controller

System.Management.dll下微软封装好了一个这样的类,该类也是我们大多数人对本地服务进行操作时,搜选方案,当时远程机也可以,但该类在操作远程机时,必须要启动你的软件以有权限操作其他机子的账户(比如:账户A在你的远程机上也有该账户,在远程机上该账户也有对WMI操作权限)。

所以说,当在控制远程机上的服务时,使用该类的局限性很大,而且不可以切换用户。

 ServiceController controller = new ServiceController("servicename", "hostname");
if (ServiceControllerStatus.Stopped == controller.Status)
{
controller.Start();
// You can use the following line to wait for service to finish starting
// you can supply a TimeSpan object to this method to timeout after that period.
controller.WaitForStatus(ServiceControllerStatus.Running);
}

运行结果,果然不负众望。

参考:

1,)http://www.codeproject.com/Articles/36268/Monitor-and-Manage-Services-on-Remote-Machines

2,)http://www.codeitive.com/0HJgVkjVeq/check-status-of-services-that-run-in-a-remote-computer-using-c.html

3,)http://www.gkspk.com/view/programming/working-with-windows-services-using-csharp-and-wmi/

c# Start/Stop/Check Status远程计算机的Windows Service的更多相关文章

  1. ECS Win2008 远程时提示"要登录到此远程计算机,您必须被授予允许通过终端登录登录的权限"的解决方法

    问题描述 ECS Windows 2008 远程登陆时提示"要登录到此远程计算机,您必须被授予允许通过终端登录登录的权限",如下图所示: 问题分析 组策略中做了设置不允许管理员组成 ...

  2. Win7 远程桌面 错误代码:5 异常处理(您的远程桌面会话即将结束 此计算机的虚拟内存可能不足。请关闭其他程序,然后重试连接远程计算机。如果问题仍然存在,请联系网络管理员或技术支持。)

    问题表现: 在用windows7 远程桌面连接其他电脑时,出现错误提示对话框—-标题为“严重错误(错误代码:5)”,内容为“您的远程桌面会话即将结束 此计算机的虚拟内存可能不足.请关闭其他程序,然后重 ...

  3. win 10 远程连接出现 "由于安全设置错误, 客户端无法连接到远程计算机. 确定你已登录到网络后.” 错误

    win 10 远程连接出现 "由于安全设置错误, 客户端无法连接到远程计算机. 确定你已登录到网络后.” 错误 解决方法如下: Step 1:打开"本地安全策略"- Wi ...

  4. (转)WS2008远程桌面连接时提示:“要登录到此远程计算机,您必须被授予允许通过终端服务登录的权限”的解决办法

    原文:http://www.chunfengxiyu.com/ws2008-mstsc-privilege.html WS2008远程桌面连接时提示:“要登录到此远程计算机,您必须被授予允许通过终端服 ...

  5. 关于win8.1“连接被远程计算机关闭”的一种解决方案

    我就是连接的时候出现"连接被远程计算机关闭",然后想着可能是win8更新之后网络协议 出问题了,后来无意中发现e信在第一次启动的时候会在网络适配器中会多出很多网卡,其中三个是带感叹 ...

  6. "客户端无法连接到远程计算机"错误的解决方法

    问题: 客户端无法连接到远程计算机. 可能没有启用远程连接或者计算机太忙不能接受新的连接. 也可能是网络问题阻止连接.请稍后重新尝试连接. 如果问题仍然存在 请与管理员联系. 解决方法: 1.首先确认 ...

  7. L2TP连接尝试失败,因为安全层在初始化与远程计算机的协商时遇到了一个处理错误(转)

    L2TP连接尝试失败,因为安全层在初始化与远程计算机的协商时遇到了一个处理错误   错误描述:“ L2TP连接尝试失败,因为安全层在初始化与远程计算机的协商时遇到了一个处理错误” 只有这个没有错误码. ...

  8. C#判断远程计算机的指定端口是否打开的代码

    如下的内容段是关于C#判断远程计算机的指定端口是否打开的内容,应该能对小伙伴有一些用. using System.Net;if(!string.IsNullOrEmpty(txtPort.Text)) ...

  9. WIN10远程计算机不支持所需的FIPS安全级别解决

    win10系统的电脑在远程xp系统或者其他系统的电脑时,提示错误,远程计算机可能不支持所需的FIPS安全级别,如果出现一以下2种错误,可以解决!   1 第一步:打开win10下的,控制面板 2 第二 ...

随机推荐

  1. ThinkPHP 关联模型中查询某条记录的父级(非查询子级)

    数据表 id      cat_name      cat_pid 76     手机.数码     0 84     手机配件        76 86     蓝牙耳机        84 从属关 ...

  2. XML解析器(转)

    常见C/C++ XML解析器有tinyxml.XERCES.squashxml.xmlite.pugxml.libxml等等,这些解析器有些是支持多语言的,有些只是单纯C/C++的.如果你是第一次接触 ...

  3. textView截取字符串-医生工作台1期

    textfield截取字符串 ios7 会崩溃 解: 之前的写法是这样的 正确的写法:   先判断markedTextRange是否为nil,   markedTextRange这个属性是啥意思呢 表 ...

  4. web项目中 集合Spring&使用junit4测试Spring

    web项目中 集合Spring 问题: 如果将 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(& ...

  5. win7 创建软链接方式

    mklink  目标文件  源文件(需要被软链的文件) Win7中的软链接详解(mklink命令) Post by 铁木箱子 in 技术杂谈 on 2011-05-24 13:13. 点评一下 评论 ...

  6. wampserver

  7. Qt 无边框窗体改变大小 完美实现(全部自己实现)

    近期,做项目用到无边框窗体,令人蛋疼的是无边框窗体大小的改变要像右边框那样,上下左右四周,而且要流畅. 网上也找了些代码,发现居然还要连接到windows事件,这显然不合常理,后来自己新建了demo, ...

  8. 使用多种客户端消费WCF RestFul服务(一)——服务端

    RestFul风格的WCF既然作为跨平台.跨语言.跨技术的一种方式出现,并且在ASP.NET API流行起来之前还是架构的首选技术之一,那么我们就来简要的介绍一下WCF在各个平台客户端的操作. 开发工 ...

  9. 使用jQuery基本过滤选择器

    <script type="text/javascript"> $(function(){ //增加第一个元素的类别 $("li:first").a ...

  10. Java学习-029-JSON 之三 -- 模仿 cssSelector 封装读取 JSON 数据方法

    前文简单介绍了如何通过 json-20141113.jar 提供的功能获取 JSON 的数据,敬请参阅:Java学习-028-JSON 之二 -- 数据读取. 了解学习过 JQuery 的朋友都知道, ...