[英]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.