2010-02-12 5 views
6

C#에서 컴퓨터 계정의 SID가 아닌 컴퓨터 SID를 가져와야합니다. 컴퓨터가 호스트 이름으로 지정되어 있지만 반드시 로컬 컴퓨터가 아니며 도메인 컴퓨터 또는 작업 그룹 컴퓨터 일 수 있습니다. 이처럼기계 SID 가져 오기 (기본 도메인 컨트롤러 포함)

private static class Helper 
    { 
     internal enum SID_NAME_USE 
     { 
      SidTypeUser = 1, 
      SidTypeGroup, 
      SidTypeDomain, 
      SidTypeAlias, 
      SidTypeWellKnownGroup, 
      SidTypeDeletedAccount, 
      SidTypeInvalid, 
      SidTypeUnknown, 
      SidTypeComputer 
     } 

     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
     private static extern bool LookupAccountName(
      string systemName, 
      string accountName, 
      byte[] sid, 
      ref int sidLen, 
      System.Text.StringBuilder domainName, 
      ref int domainNameLen, 
      out SID_NAME_USE peUse); 

     public static SecurityIdentifier LookupAccountName(
      string systemName, 
      string accountName, 
      out string strDomainName, 
      out SID_NAME_USE accountType) 
     { 
      const int ERROR_INSUFFICIENT_BUFFER = 122; 

      int lSidSize = 0; 
      int lDomainNameSize = 0; 

      //First get the required buffer sizes for SID and domain name. 
      LookupAccountName(systemName, 
           accountName, 
           null, 
           ref lSidSize, 
           null, 
           ref lDomainNameSize, 
           out accountType); 

      if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER) 
      { 
       //Allocate the buffers with actual sizes that are required 
       //for SID and domain name. 
       byte[] sid = new byte[lSidSize]; 
       var sbDomainName = new System.Text.StringBuilder(lDomainNameSize); 

       if (LookupAccountName(systemName, 
             accountName, 
             sid, 
             ref lSidSize, 
             sbDomainName, 
             ref lDomainNameSize, 
             out accountType)) 
       { 
        strDomainName = sbDomainName.ToString(); 
        return new SecurityIdentifier(sid, 0); 
       } 
      } 

      throw new Win32Exception(); 
     } 
    } 

및 사용 : 나는 중 LookupAccountName API 함수 호출이 헬퍼 클래스를 사용

Helper.SID_NAME_USE accountType; 
string refDomain; 
SecurityIdentifier sid = Helper.LookupAccountName("falcon.mydomain.local", "falcon", out refDomain, out accountType); //Domain computer 

SecurityIdentifier sid = Helper.LookupAccountName("rat", "rat", out refDomain, out accountType); //Workgroup computer 

내 유일한 문제는, 컴퓨터가 주 도메인 컨트롤러 인 경우이 작동하지 않는 (나는 필요 이 경우 도메인 SID를 얻기 위해).

답변

2

이 나타납니다 대부분의 컴퓨터는 다음을 수행하는 것이 :

중 LookupAccountName ("", "컴퓨터 이름", ...); ConvertSidToStringSid (...)

도메인 컨트롤러의 경우 컴퓨터 이름 매개 변수에 달러 기호를 추가 한 다음 반환 된 SID의 마지막 세그먼트를 삭제해야합니다.

관련 문제