简体   繁体   中英

Restart a windows service on windows remote server c#

I'm trying to restart a service on a remote server

    public void RestartService(string service, string server)
    {
        ServiceController service = new ServiceController("****", "****");
        try
        {
            string username = "****";
            string password = "****";
            server = "******";
            ConnectionOptions connectopt = new ConnectionOptions();
            connectopt.Username = username;
            connectopt.Password = password;
            ManagementScope scope = new ManagementScope(@"\\'" + server + "'\\root\\cimv2", connectopt);
            scope.Options = connectopt;
            SelectQuery query = new SelectQuery("select * from Win64_Service where Name = '" +****+ "'");
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
            {
                ManagementObjectCollection collection = searcher.Get();
                {

                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running);
                }

            }
        }

        catch (Exception ex)
        {
            ex.ToString();
        }

    }
}

}

But I'm getting the error - RPC server is not available. I've tried all the workarounds that are given in google. But still nothing helps

You can use with psexec.exe

psexec \\RemotePCName -u username -p password cmd.exe "/c sc stop servicename"  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM