如何从 Active Directory 检索 SAMAccountName

本文关键字:检索 SAMAccountName Directory Active | 更新日期: 2023-09-27 18:30:50

我实现了一个返回活动目录用户列表的方法,我想像这样Domain'Administrator检索SAMAccountName。

这是我使用的方法:

public Collection<software_user> GetUsersFromAD(String adConnectionString)
{
    var users = new Collection<software_user>();
    using (var directoryEntry = new DirectoryEntry(adConnectionString))
    {
        var directorySearcher = new DirectorySearcher(directoryEntry);
        directorySearcher.Filter = "(&(objectClass=user))";
        var propertiesToLoad = new[] 
        { 
           "SAMAccountName", 
           "displayName", 
           "givenName", 
           "sn", 
           "mail", 
           "userAccountControl", 
           "objectSid" 
        };
        directorySearcher.PropertiesToLoad.AddRange(propertiesToLoad);
        foreach (SearchResult searchEntry in directorySearcher.FindAll())
        {
            var userEntry = searchEntry.GetDirectoryEntry();
            var ldapUser = new software_user();
            ldapUser.User_name = NullHandler.GetString(userEntry.Properties["displayName"].Value);
            if (string.IsNullOrEmpty(ldapUser.User_name))
               continue;
            ldapUser.User_name = NullHandler.GetString(userEntry.Properties["SAMAccountName"].Value);
            ldapUser.email = NullHandler.GetString(userEntry.Properties["mail"].Value);
            ldapUser.user_shortname = NullHandler.GetString(userEntry.Properties["givenName"].Value);
            var userAccountControl = (int)userEntry.Properties["userAccountControl"].Value;
            //ldapUser.IsActive = (userAccountControl & UF_ACCOUNTDISABLE) != UF_ACCOUNTDISABLE;
            var sid = new SecurityIdentifier((byte[])userEntry.Properties["objectSid"][0], 0).Value;
            //ldapUser.SId = sid;
            users.Add(ldapUser);
         }
    }
    return users;
}

如何从 Active Directory 检索 SAMAccountName

首先:Domain'Administrator不是SAM帐户名称!SAM 帐户名称是唯一的(在整个域中)名称,长度不超过 20 个字符 - 通常是您的"Windows 用户名"(例如 Administrator ) - 但它不包括域名。由domain'username组成的值不会存储在Active Directory中的任何地方!


如果使用的是 .NET 3.5 及更高版本,则应签出 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在这里阅读所有关于它的信息:

  • 在 .NET Framework 3.5 中管理目录安全主体
  • MSDN 文档 on System.DirectoryServices.AccountManagement

基本上,您可以定义域上下文并在 AD 中轻松查找用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
   // do something here....     
   string samAccountName = user.SamAccountName;
}

新的 S.DS.AM 使在AD中玩弄用户和组变得非常容易!

如果要搜索整个用户组(或组或计算机),可以使用PrincipalSearcher和"按示例查询"主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the last name (Surname) of "Miller"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Surname = "Miller";
// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
}

您可以使用对象的 SID 和 System.Security.Principal.SecurityIdentifier.Translate 命令将用户作为可分辨名称转换为 DOMAIN''SAMaccount 表单。

public Collection<software_user> GetUsersFromAD(String adConnectionString)
    {
            var users = new Collection<software_user>();
            using (var directoryEntry = new DirectoryEntry(adConnectionString))
            {
                    var directorySearcher = new DirectorySearcher(directoryEntry);
                    directorySearcher.Filter = "(&(objectClass=user))";
                    var propertiesToLoad = new[] 
                    { 
                         "SAMAccountName", 
                         "displayName", 
                         "givenName", 
                         "sn", 
                         "mail", 
                         "userAccountControl", 
                         "objectSid" 
                    };
                    directorySearcher.PropertiesToLoad.AddRange(propertiesToLoad);
                    foreach (SearchResult searchEntry in directorySearcher.FindAll())
                    {
                            var userEntry = searchEntry.GetDirectoryEntry();
                            var ldapUser = new software_user();
                            ldapUser.User_name = NullHandler.GetString(userEntry.Properties["displayName"].Value);
                            if (string.IsNullOrEmpty(ldapUser.User_name))
                                 continue;
                            ldapUser.User_name = NullHandler.GetString(userEntry.Properties["SAMAccountName"].Value);
                            ldapUser.email = NullHandler.GetString(userEntry.Properties["mail"].Value);
                            ldapUser.user_shortname = NullHandler.GetString(userEntry.Properties["givenName"].Value);
                            var userAccountControl = (int)userEntry.Properties["userAccountControl"].Value;
                            //ldapUser.IsActive = (userAccountControl & UF_ACCOUNTDISABLE) != UF_ACCOUNTDISABLE;
                            SecurityIdentifier sid = new SecurityIdentifier((byte[])userEntry.Properties["objectSid"][0], 0).Value;
    -->                     NTAccount account = (NTAccount) sid.Translate(typeof(NTAccount));
    -->                     ldapUser.User_name = account.ToString();
                            //ldapUser.SId = sid;
                            users.Add(ldapUser);
                     }
            }
            return users;
    }