如何在不同的服务器上以Programitically方式重新启动服务 [英] How to Restart Service Programitically on diffrent servers

查看:94
本文介绍了如何在不同的服务器上以Programitically方式重新启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows窗体应用程序,我想从中重新启动各种不同服务器的服务。根据按钮单击事件在文本框中输入的值,应用程序应连接到该服务器并启动服务。为此,我编写了以下代码,它显示它正在工作但实际上它没有工作没有任何错误。如果任何budy有任何类型的解决方案,请告诉我。

I am having a Windows Forms application, from which I want to restart services for various different servers. According to the value entered in textbox on button click event, the application should connect to that server and service should start. For this I have written the following code and it is showing that it is working but actually it is not working without any error. If any budy having any type of solution please let me know.

class Program
{
    static void Main(string[] args)
    {
        Impersonate.ImpersonateNow("ip", "machineName", "password");

        string serviceName = "AxInstSV";
          int timeoutMilliseconds = 1000;
        ServiceController service = new ServiceController(serviceName);
        try
        {
            int millisec1 = Environment.TickCount;
            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

            if (service.Status == ServiceControllerStatus.Running || service.Status == ServiceControllerStatus.Paused)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }
            // count the rest of the timeout
            int millisec2 = Environment.TickCount;
            timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
            if (service.Status == ServiceControllerStatus.Stopped || service.Status == ServiceControllerStatus.StopPending)
            {
                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
        }
        catch
        {
            throw;
        }

        Console.WriteLine("Service has been restarted");
        Console.ReadLine();
}

推荐答案

很好的解决方案,特别是在Main方法的第一行用户模拟用户。

这对于在远程PC上访问和注入所有必要的用户权限非常必要。



但是!!您是否曾见过ServiceController ctor的第三次重载?)

如果没有,请在MSDN上查看。它为您提供了一个额外的参数,机器名称,或者在您的情况下它可以是一个IP地址。



和最后一个,是否有任何远程机器位于同一个域名?如果没有,你的方法无论如何都会失败。
Nice solution, especially usage impersonation of user at first line in Main method.
This was quite necessary for reaching and injecting all of the necessary user rights on remote PC.

But!! Have you ever seen the third overload of ServiceController ctor?)
If not , please check it on MSDN. It gives to you 1 additional parameter,machine name ,or in your case it coul be an IP address.

And the last one, Does any of remote machine located in the same domain ? If not , you approach will fail anyway.


这篇关于如何在不同的服务器上以Programitically方式重新启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆