我正在尝试编写一个程序,该程序将连接到远程服务器并显示某些服务状态。这项服务也是由我们(我的公司)写的。
为此,我编写了一个控制台应用程序,代码是
static void Main(string[] args)
{
ConnectionOptions options = new ConnectionOptions();
options.Password = "mypassword";
options.Username = "Administrator";
options.Impersonation =
System.Management.ImpersonationLevel.Impersonate;
ManagementScope scope =
new ManagementScope(
"\\\\ip_of_the_server\\root\\cimv2", options);
scope.Connect();
ServiceController svc = new ServiceController("My_Service_Name", "ip_of_the_server");
var status = svc.Status.ToString();
Console.WriteLine(svc.DisplayName + " : " status);
}但我不能让它起作用。我得到的错误是:
Cannot open Service Control Manager on computer 'ip_of_the_server'. This operation might require other privileges.内部异常:“访问被拒绝”。
堆栈跟踪:
at System.ServiceProcess.ServiceController.GetDataBaseHandleWithAccess(String machineName, Int32 serviceControlManaqerAccess)
at System.ServiceProcess.ServiceController.GetDataBaseHandleWithConnectAccess()
at System.ServiceProcess.ServiceController.GenerateNames()
at System.ServiceProcess.ServiceController.get_ServiceName()
at System.ServiceProcess.ServiceController.GenerateStatus()
at System.ServiceProcess.ServiceController.get_Status()
at ServiceConsole.Program.Main(String[] args) in c:\Users\Kandroid\Documents\Visual Studio 2013\Projects\ServiceConsole\ServiceConsole\Program.cs:line 33
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()知道怎么解决吗??
发布于 2014-08-27 11:42:47
由于您已经设置了一个管理范围,所以只需使用WQL查询WMI提供程序是否有正确的WMI对象,在本例中是服务,如下所示:
var svc = new ManagementObjectSearcher(
scope,
new ObjectQuery("Select Status,State from Win32_Service where Name='My_Service_Name'"))
.Get()
.GetEnumerator();
if (svc.MoveNext())
{
var status = svc.Current["Status"].ToString();
var state = svc.Current["State"].ToString();
Console.WriteLine("service status {0}", status);
// if not running, StartService
if (!String.Equals(state, "running",StringComparison.InvariantCultureIgnoreCase) {
( (ManagementObject) svc.Current ).InvokeMethod("StartService", new object[] {});
}
}
else
{
Console.WriteLine("service not found");
}ManagementObjectSearcher负责检索WMI托管对象的集合。ObjectQuery将从作用域返回类的实例。我们可以执行基本的select语句来选择和项目结果集。
迭代器返回一个ManagementObjectBase,它作为Item访问器从返回的实例中检索属性。
https://stackoverflow.com/questions/25525962
复制相似问题