如何从本地网络中的远程计算机控制windows服务
本文关键字:计算机控制 windows 服务 本地网络 | 更新日期: 2023-09-27 18:18:42
我首先道歉,因为这可能是重复的问题。但我用谷歌搜索了很多,甚至找到了两个非常相似的,比如:
- 如何使用ServiceController远程控制Windows服务?
但不幸的是,他们都不适合我。
我开发了一个运行在windows server 2008 R2标准机上的windows服务。
服务运行良好,工作良好,因为它应该工作。
我的问题是我想做一个桌面应用程序,将运行在我们的本地网络。从这个应用程序中,我想做一些基本的操作,比如获取服务状态,停止和重新启动。
这是我的工作。
private void WSControllerForm_Load(object sender, System.EventArgs e)
{
ConnectionOptions options = new ConnectionOptions();
options.Password = "password";
options.Username = "Administrator";
options.Impersonation =
System.Management.ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authority = "NTLMDOMAIN:IQ-HOME";
options.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope scope =
new ManagementScope(@"''RTOKEN-SERVER'root'cimv2", options);
scope.Connect(); //checked its connected
// Make a connection to a remote computer.
// Replace the "FullComputerName" section of the
// string "''''FullComputerName''root''cimv2" with
// the full computer name or IP address of the
// remote computer.
ServiceController service = new ServiceController("Recharger Token", "RTOKEN-SERVER");
service.Refresh();
MessageBox.Show(service.Status.ToString()); //Error raised: {"Cannot open Service Control Manager on computer 'rToken-server'. This operation might require other privileges."}
}
请让我知道我做错了什么?我该如何实现我的目标?
注:我的开发PC是Windows 7 Ultimate,其中作为服务铺设在Windows Server 2008 R2标准。服务在网络服务下运行。(我把它改为管理员登录,但没有运气)
谢谢
试试这段代码,它使用您的ManagementScope,但使用我在注释中提供的链接中的managentobjectsearcher表单查询服务。
如果不是这样的话,我会调查一下你的用户是否有权做你需要做的事情。
private void WSControllerForm_Load(object sender, System.EventArgs e)
{
ConnectionOptions options = new ConnectionOptions();
options.Password = "password";
options.Username = "Administrator";
//i'm not 100% sure these 4 lines are needed - try without if it still fails
options.Impersonation =
System.Management.ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authority = "NTLMDOMAIN:RTOKEN-SERVER";
options.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope scope =
new ManagementScope(@"''RTOKEN-SERVER'root'cimv2", options);
scope.Connect();
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher();
moSearcher.Scope = scope;
moSearcher.Query = new ObjectQuery("SELECT * FROM win32_Service WHERE Name ='Recharger Token'");
ManagementObjectCollection mbCollection = moSearcher.Get();
foreach (ManagementObject oReturn in mbCollection)
{
//invoke start
//ManagementBaseObject outParams = oReturn.InvokeMethod("StartService", null, null);
//invoke stop
//ManagementBaseObject outParams = oReturn.InvokeMethod("StopService", null, null);
//get result
//string a = outParams["ReturnValue"].ToString();
//get service state
string state = oReturn.Properties["State"].Value.ToString().Trim();
MessageBox.Show(state);
}
}