我正在寻找一种使用Delphi代码提取计算机SID的方法. SysInternals有一个名为PsGetSid的工具可以做到这一点,但我不能在我的应用程序中使用它.我在Google中搜索了一个代码示例,找不到一个.
我怎样才能在Delphi中实现这一目标?
请帮忙.
解决方法
这是使用
LookupAccountName
WinAPi函数的示例,如@MikeKwan建议的那样.
{$APPTYPE CONSOLE} uses Windows,SysUtils; function ConvertSidToStringSid(Sid: PSID; out StringSid: PChar): BOOL; stdcall; external 'ADVAPI32.DLL' name {$IFDEF UNICODE} 'ConvertSidToStringSidW'{$ELSE} 'ConvertSidToStringSidA'{$ENDIF}; function SIDToString(ASID: PSID): string; var StringSid : PChar; begin if not ConvertSidToStringSid(ASID,StringSid) then RaiseLastWin32Error; Result := string(StringSid); end; function GetLocalComputerName: string; var nSize: DWORD; begin nSize := MAX_COMPUTERNAME_LENGTH + 1; SetLength(Result,nSize); if not GetComputerName(PChar(Result),{var}nSize) then begin Result := ''; Exit; end; SetLength(Result,nSize); end; function GetComputerSID:string; var Sid: PSID; cbSid: DWORD; cbReferencedDomainName : DWORD; ReferencedDomainName: string; peUse: SID_NAME_USE; Success: BOOL; lpSystemName : string; lpAccountName: string; begin Sid:=nil; try lpSystemName:=''; lpAccountName:=GetLocalComputerName; cbSid := 0; cbReferencedDomainName := 0; // First call to LookupAccountName to get the buffer sizes. Success := LookupAccountName(PChar(lpSystemName),PChar(lpAccountName),nil,cbSid,cbReferencedDomainName,peUse); if (not Success) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then begin SetLength(ReferencedDomainName,cbReferencedDomainName); Sid := AllocMem(cbSid); // Second call to LookupAccountName to get the SID. Success := LookupAccountName(PChar(lpSystemName),Sid,PChar(ReferencedDomainName),peUse); if not Success then begin FreeMem(Sid); Sid := nil; RaiseLastOSError; end else Result := SIDToString(Sid); end else RaiseLastOSError; finally if Assigned(Sid) then FreeMem(Sid); end; end; begin try Writeln(GetComputerSID); except on E:Exception do Writeln(E.Classname,':',E.Message); end; Writeln('Press Enter to exit'); Readln; end.