How to restart service remotely?

冷暖自知 提交于 2020-01-12 13:48:34

问题


I can start or stop service remotely from .net project.

ConnectionOptions options = new ConnectionOptions();
options.Username = @"192.168.36.22\test";
options.Password = "test";
ManagementScope scope = new ManagementScope(@"\\192.168.36.22\root\cimv2", options);
scope.Connect();


ManagementOperationObserver Stop = new ManagementOperationObserver();
Stop.Completed += new CompletedEventHandler(Stop_CallBack);
try
{
    string NameServices = "ArcGIS Server";
    WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_Service  WHERE Name=\"" + NameServices + "\"");
    ManagementObjectSearcher find = new ManagementObjectSearcher(scope, query);
    foreach (ManagementObject spooler in find.Get())
    {
        spooler.InvokeMethod("StopService", new object[] { });
        spooler.InvokeMethod(Start, "StopService", new object[] { });
    }
 }
....

How can I restart this service?


回答1:


You could use the ServiceController class like so:

ServiceController sc = new ServiceController("ArcGIS Server", "192.168.36.22");

sc.Start();
sc.Stop();

This saves you having to write all that code to interact with WMI. Note to use the ServiceController class, you'll have to add a reference to the System.ServiceProcess assembly.




回答2:


Service controller didn't work for me, so I used Cmd to do it.

Process.Start("CMD.exe", "/C sc \\\\remoteMachine stop \"serviceName\"&sc \\\\remoteMachine start \"serviceName\"");

To overcome credentials issue, I used class from this https://stackoverflow.com/a/5433640/2179222 answer.

So in the end It looked like this:

    private static void RestartService(string remoteMachine, string serviceName, string userName, string password)
    {
        using (new NetworkConnection($"\\\\{remoteMachine}", new NetworkCredential(userName, password)))
        {
            Process.Start("CMD.exe", $"/C sc \\\\{remoteMachine} stop \"{serviceName}\"&sc \\\\{remoteMachine} start \"{serviceName}\"");
        }
    }



回答3:


I have come across a similar problem when I tried to connect, just add your machine name as admin in the 'users' group of the target machine and you will be able to fetch the data.



来源:https://stackoverflow.com/questions/18405884/how-to-restart-service-remotely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!