Como posso obter o SID da conta do Windows atual?
Pergunta
Eu estou procurando uma maneira fácil de obter o SID para a conta de usuário atual do Windows. Eu sei que posso fazê-lo através do WMI, mas eu não quero ir por esse caminho.
Desculpas a todos que responderam em C # para não especificá-lo do C ++. : -)
Solução
Em Win32, chamada GetTokenInformation , passando um identificador de token eo TokenUser
constante. Ele vai preencher um href="http://msdn.microsoft.com/en-us/library/aa379634.aspx" rel="noreferrer"> TOKEN_USER estrutura para você. Um dos elementos em que há SID do usuário. É um BLOB (binário), mas você pode transformá-lo em uma string usando ConvertSidToStringSid .
Para se apossar do identificador de token atual, use OpenThreadToken ou OpenProcessToken .
Se você preferir ATL, ele tem a CAccessToken classe, que tem todos os tipos de coisas interessantes nela.
.NET tem a Thread.CurrentPrinciple propriedade, que retorna uma referência IPrincipal. Você pode obter o SID:
IPrincipal principal = Thread.CurrentPrincipal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
if (identity != null)
Console.WriteLine(identity.User);
Também em .NET, você pode usar WindowsIdentity.GetCurrent (), que retorna o ID do usuário atual:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity != null)
Console.WriteLine(identity.User);
Outras dicas
Isso deve lhe dar o que você precisa:
usando System.Security.Principal;
...
var sid = WindowsIdentity.GetCurrent () Usuários;.
A propriedade usuário de WindowsIdentity retorna o SID, por MSDN Docs
ATL::CAccessToken accessToken;
ATL::CSid currentUserSid;
if (accessToken.GetProcessToken(TOKEN_READ | TOKEN_QUERY) &&
accessToken.GetUser(¤tUserSid))
return currentUserSid.Sid();
CodeProject tem alguns métodos diferentes que você pode tentar ... Você não mencionou que idiomas você queria uma solução.
Se você quiser acessá-lo através de um arquivo de lote ou algo assim, você pode olhar como PsGetSid por Sysinternals . Ele traduz SIDs para nomes e vice-versa.
Em C # você pode usar
using Microsoft.Win32.Security;
...
string username = Environment.UserName + "@" + Environment.GetEnvironmentVariable("USERDNSDOMAIN");
Sid sidUser = new Sid (username);
Ou ...
using System.Security.AccessControl;
using System.Security.Principal;
...
WindowsIdentity m_Self = WindowsIdentity.GetCurrent();
SecurityIdentifier m_SID = m_Self.Owner;");
Eu encontrei outra maneira de obter SID:
System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent();
string sid = id.User.AccountDomainSid.ToString();
E em código nativo:
function GetCurrentUserSid: string;
hAccessToken: THandle;
userToken: PTokenUser;
dwInfoBufferSize: DWORD;
dw: DWORD;
if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, ref hAccessToken) then
dw <- GetLastError;
if dw <> ERROR_NO_TOKEN then
RaiseLastOSError(dw);
if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, ref hAccessToken) then
RaiseLastOSError;
try
userToken <- GetMemory(1024);
try
if not GetTokenInformation(hAccessToken, TokenUser, userToken, 1024, ref dwInfoBufferSize) then
RaiseLastOSError;
Result <- SidToString(userToken.User.Sid);
finally
FreeMemory(userToken);
finally
CloseHandle(hAccessToken);
Você não especificou o idioma desejado. Mas se você estiver a fim de C # Este artigo oferece tanto o método WMI, bem como uma mais rápida (enquanto mais detalhado) Método utilizando a API Win32.
http://www.codeproject.com/KB/cs/processownersid.aspx
Eu não acho que há atualmente uma outra maneira de fazer isso sem usar WMI ou a API Win32.
Este é o mais curto de todos eles eu acredito.
UserPrincipal.Current.Sid;
Disponível com .net> = 3,5
Esta questão é marcado como c++
E eu respondo em linguagem c++
, Então, eu recomendo o uso de WMI ferramenta:
Assim, como WMI comandos no powershell
, abaixo comando get SID
de usuário system-pc1
:
Get-WmiObject win32_useraccount -Filter "name = 'system-pc1'" | Select-Object sid
Primeiro, você precisa obter username
atual com code
abaixo:
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
Agora você pode experimentar com a linguagem WQL
e executar essa consulta em c++
como o fole (neste exemplo, eu usei de nome de usuário system-pc1
em consulta WQL_WIN32_USERACCOUNT_QUERY
:
#define NETWORK_RESOURCE "root\\CIMV2"
#define WQL_LANGUAGE "WQL"
#define WQL_WIN32_USERACCOUNT_QUERY "SELECT * FROM Win32_Useraccount where name='system-pc1'"
#define WQL_SID "SID"
IWbemLocator *pLoc = 0; // Obtain initial locator to WMI to a particular host computer
IWbemServices *pSvc = 0; // To use of connection that created with CoCreateInstance()
ULONG uReturn = 0;
HRESULT hResult = S_OK; // Result when we initializing
IWbemClassObject *pClsObject = NULL; // A class for handle IEnumWbemClassObject objects
IEnumWbemClassObject *pEnumerator = NULL; // To enumerate objects
VARIANT vtSID = { 0 }; // OS name property
// Initialize COM library
hResult = CoInitializeEx(0, COINIT_MULTITHREADED);
if (SUCCEEDED(hResult))
{
// Initialize security
hResult = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
if (SUCCEEDED(hResult))
{
// Create only one object on the local system
hResult = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID*)&pLoc);
if (SUCCEEDED(hResult))
{
// Connect to specific host system namespace
hResult = pLoc->ConnectServer(TEXT(NETWORK_RESOURCE), NULL, NULL,
0, NULL, 0, 0, &pSvc);
if (SUCCEEDED(hResult))
{
/* Set the IWbemServices proxy
* So the impersonation of the user will be occurred */
hResult = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE,
NULL, EOAC_NONE);
if (SUCCEEDED(hResult))
{
/* Use the IWbemServices pointer to make requests of WMI
* For example, query for user account */
hResult = pSvc->ExecQuery(TEXT(WQL_LANGUAGE), TEXT(WQL_WIN32_USERACCOUNT_QUERY),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (SUCCEEDED(hResult))
{
// Go to get the next object from IEnumWbemClassObject
pEnumerator->Next(WBEM_INFINITE, 1, &pClsObject, &uReturn);
if (uReturn != 0)
{
// Get the value of the "sid, ..." property
pClsObject->Get(TEXT(WQL_SID), 0, &vtSID, 0, 0);
VariantClear(&vtSID);
// Print SID
wcout << vtSID.bstrVal;
pClsObject->Release();
pClsObject = NULL;
}
}
}
}
}
}
// Cleanup
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
// Uninitialize COM library
CoUninitialize();
Este exemplo faz trabalhos corretamente!