2

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;
    }
}
4

2 回答 2

1

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

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

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

如果您很好 - 请在异常消息(或链接)中提供有关帐户需要哪些权限的详细说明,针对您的特定情况有哪些良好做法以及可能的廉价解决方案(即“该程序需要 YYYY 的 XXXX 权限。您可以以管理员身份运行以进行测试,但不推荐用于生产”)。

于 2013-08-30T19:16:07.920 回答
0

I implemented the AutorizedToStopWindowsService() method that I described in my updated question and it's working quite well.

于 2013-10-02T15:30:53.417 回答