[英]How to get a Windows Service logon credentials
有很多关于如何为 Windows 服务设置用户登录凭据的示例,但是我无法发现您是如何首先确定为该 Windows 服务设置的当前凭据的。
我想做的是:
If(WinService.logonCredentials == LocalUser)
WinService.logonCredentials = new logonCredentials;
是否有一个我可以访问的类可以为我提供所需的数据和/或可能的其他 Windows 服务设置?
我不确定,但是如果您不能使用 .net 中内置的类来做到这一点,那么可能唯一的方法就是使用 WMI。
这是 Win32Service 类:
class Win32_Service : Win32_BaseService
{
boolean AcceptPause;
boolean AcceptStop;
string Caption;
uint32 CheckPoint;
string CreationClassName;
string Description;
boolean DesktopInteract;
string DisplayName;
string ErrorControl;
uint32 ExitCode;
datetime InstallDate;
string Name;
string PathName;
uint32 ProcessId;
uint32 ServiceSpecificExitCode;
string ServiceType;
boolean Started;
string StartMode;
string StartName;
string State;
string Status;
string SystemCreationClassName;
string SystemName;
uint32 TagId;
uint32 WaitHint;
};
这就是你要问的:
string StartName;
我使用 PowerShell 在我的笔记本电脑上获取有关“远程桌面”服务的数据,我得到了更多这样的数据(其中一些数据是来自 Win32_BaseService 的属性,而不是 Win32Service):
DesktopInteract : False
DisconnectedSessions : 1
DisplayName : Remote desktop services
ErrorControl : Normal
ExitCode : 1077
InstallDate :
Name : TermService
PathName : C:\Windows\System32\svchost.exe -k NetworkService
ProcessId : 0
ServiceSpecificExitCode : 0
ServiceType : Share Process
Started : False
StartMode : Manual
StartName : NT Authority\NetworkService
State : Stopped
Status : OK
SystemCreationClassName : Win32_ComputerSystem
SystemName : NOTEBOOK
TagId : 0
TotalSessions : 2
WaitHint : 0
我无法帮助 C# 中的 WMI。 也许你会在你正在使用的类中的某个地方找到 StartName 属性(我不知道它是什么类,因为你没有写)。
以下是如何在 C# 中使用 WMI 检索此信息:
public string GetWindowsServiceLoginCredentials(string serviceName)
{
var credentials = (
from x
in new ManagementObjectSearcher($"SELECT StartName FROM Win32_Service WHERE Caption = '{serviceName}'")
.Get()
.Cast<ManagementObject>()
select
x.GetPropertyValue("StartName")).FirstOrDefault();
return credentials != null ? credentials.ToString() : "";
}
您可以使用它来获取服务的其他属性,只需更改您感兴趣的属性的“StartName”即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.