我是否有权启动/停止Windows服务?

时间:2013-08-30 18:58:59

标签: c# windows-services

C#中是否有办法确定我是否有权启动和停止Windows服务?

如果我的进程在NETWORK SERVICE帐户下运行并且我尝试停止服务,我将收到“拒绝访问”异常,这很好,但我希望能够在尝试之前确定我是否获得授权操作

我正在尝试改进看起来像这样的代码:

var service = new ServiceController("My Service");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));

类似于:

if (AmIAuthorizedToStopWindowsService())
{
    var service = new ServiceController("My Service");
    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
}

更新 这样的事情怎么样:

private bool AutorizedToStopWindowsService()
{
    try
    {
        // Try to find one of the well-known services
        var wellKnownServices = new[]
        { 
            "msiserver",    // Windows Installer
            "W32Time"       // Windows Time
        };
        var services = ServiceController.GetServices();
        var service = services.FirstOrDefault(s => s.ServiceName.In(wellKnownServices) && s.Status.In(new[] { ServiceControllerStatus.Running, ServiceControllerStatus.Stopped }));

        // If we didn't find any of the well-known services, we'll assume the user is not autorized to stop/start services
        if (service == null) return false;

        // Get the current state of the service
        var currentState = service.Status;

        // Start or stop the service and then set it back to the original status
        if (currentState == ServiceControllerStatus.Running)
        {
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5));
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(5));
        }
        else
        {
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(5));
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5));
        }

        // If we get this far, it means that we successfully stopped and started a windows service
        return true;
    }
    catch
    {
        // An error occurred. We'll assume it's due to the fact the user is not authorized to start and stop services
        return false;
    }
}

2 个答案:

答案 0 :(得分:1)

不是真的。您可以尝试推断您的帐户是否具有权限(例如管理员或域管理员组的成员),这可能足以满足您的需求。

Windows中的权限可以在非常精细的对象/操作上设置,因此任何特定的成员资格都不一定保证您的帐户对特定对象的特定操作具有权限,即使它具有对其他对象进行类似/相同操作的权限。 / p>

处理的方法是尝试操作并处理异常。

如果您还不错 - 请提供有关帐户所需权限的异常消息(或链接)中的详细说明,针对您的具体案例的哪些好方法以及可能的廉价解决方案(即“此程序需要XXXX权限YYYY。您可以作为管理员运行测试,但不建议用于生产“)。

答案 1 :(得分:0)

我实现了我在更新后的问题中描述的AutorizedToStopWindowsService()方法,并且它运行良好。