我有权启动/停止windows服务吗
本文关键字:windows 服务 停止 启动 | 更新日期: 2023-09-27 18:29:45
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;
}
}
不是。您可以尝试推断您的帐户是否具有权限(如管理员或域管理员组的成员),这可能足以满足您的情况。
Windows中的权限可以设置在非常精细的对象/操作上,因此任何特定的成员身份都不一定能保证您的帐户对特定对象具有特定操作的权限,即使它对其他对象具有类似/相同操作的权限。
处理方法是尝试操作并处理异常。
如果你很好,请在异常消息(或链接)中提供详细说明,说明帐户需要什么权限,您的特定情况下有什么好的做法,以及什么是可能的廉价解决方案(即"此程序需要YYYY的XXXX权限。您可以以管理员身份运行测试,但不建议用于生产")。
我实现了我在更新的问题中描述的AutorizedToStopWindowsService()方法,它运行得很好。