使用 C Sharp 迭代活动目录中的组

发布于 2025-01-08 14:50:36 字数 482 浏览 0 评论 0原文

我需要能够从任何服务器执行一个程序,该程序可以遍历活动目录中的组并检查该组中用户的某些属性。这是我到目前为止所拥有的:

public static bool searchUser(string domain, string userName, string password, string objectDN)
{
    DirectoryEntry obj = new DirectoryEntry("LDAP://" + domain + "/" + objectDN, userName, password);
    if (obj.Properties["objectCategory"].ToString().Equals("group"))
    {
        object users = obj.Invoke("Members", null);
        foreach (object members in users) 
        { }
    }
}

I need to be able to execute a program from any server that could iterate through a group in active directory and check certain properties of the users in that group. This is what I have so far:

public static bool searchUser(string domain, string userName, string password, string objectDN)
{
    DirectoryEntry obj = new DirectoryEntry("LDAP://" + domain + "/" + objectDN, userName, password);
    if (obj.Properties["objectCategory"].ToString().Equals("group"))
    {
        object users = obj.Invoke("Members", null);
        foreach (object members in users) 
        { }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿挽旧人 2025-01-15 14:50:36

以下代码需要进行大量重构,但我上次检查时它已经正常工作了一个月

    private List<DirectoryUser> GetUsersInGroup(string groupName)
    {
        List<DirectoryUser> directoryUsers = new List<DirectoryUser>();

        try
        {
            ResultPropertyValueCollection members = null;

            using (var entry = new DirectoryEntry(_server))
            {
                entry.Path = "LDAP://" + _usersRoot;
                entry.Username = _domain + @"\" + _serviceAccountUsername;
                entry.Password = _serviceAccountPassword;
                entry.AuthenticationType = AuthenticationTypes.Secure;

                using (DirectorySearcher searcher = new DirectorySearcher(entry))
                {
                    searcher.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
                    searcher.PropertiesToLoad.Add("member");

                    SearchResult result = searcher.FindOne();

                    if (result == null)
                        return directoryUsers;

                    members = result.Properties["member"];
                }
            }

            if (members == null || members.Count == 0)
                return directoryUsers;

            foreach (var member in members)
            {
                using (var entry = new DirectoryEntry(_server))
                {
                    entry.Path = "LDAP://" + member;
                    entry.Username = _domain + @"\" + _serviceAccountUsername;
                    entry.Password = _serviceAccountPassword;
                    entry.AuthenticationType = AuthenticationTypes.Secure;

                    using (DirectorySearcher searcher = new DirectorySearcher(entry))
                    {
                        searcher.Filter = "(objectClass=user)";
                        searcher.SearchScope = SearchScope.Base;

                        searcher.PropertiesToLoad.Add("mail");
                        searcher.PropertiesToLoad.Add("givenName");
                        searcher.PropertiesToLoad.Add("sn");
                        searcher.PropertiesToLoad.Add("sAMAccountName");
                        searcher.PropertiesToLoad.Add("telephoneNumber");

                        SearchResult result = searcher.FindOne();

                        if (result == null)
                            continue;

                        var dirUser = new DirectoryUser();
                        dirUser.Username = Convert.ToString(result.Properties["sAMAccountName"][0]);
                        dirUser.FirstName = Convert.ToString(result.Properties["givenName"][0]);
                        dirUser.LastName = Convert.ToString(result.Properties["sn"][0]);
                        dirUser.Email = Convert.ToString(result.Properties["mail"][0]);
                        dirUser.Phone = Convert.ToString(result.Properties["telephoneNumber"][0]);

                        directoryUsers.Add(dirUser);


                    }

                }
            }


        }
        catch { }

        return directoryUsers;

    }

The following code needs to be refactored terribly but it's been working right for a month last time I checked

    private List<DirectoryUser> GetUsersInGroup(string groupName)
    {
        List<DirectoryUser> directoryUsers = new List<DirectoryUser>();

        try
        {
            ResultPropertyValueCollection members = null;

            using (var entry = new DirectoryEntry(_server))
            {
                entry.Path = "LDAP://" + _usersRoot;
                entry.Username = _domain + @"\" + _serviceAccountUsername;
                entry.Password = _serviceAccountPassword;
                entry.AuthenticationType = AuthenticationTypes.Secure;

                using (DirectorySearcher searcher = new DirectorySearcher(entry))
                {
                    searcher.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
                    searcher.PropertiesToLoad.Add("member");

                    SearchResult result = searcher.FindOne();

                    if (result == null)
                        return directoryUsers;

                    members = result.Properties["member"];
                }
            }

            if (members == null || members.Count == 0)
                return directoryUsers;

            foreach (var member in members)
            {
                using (var entry = new DirectoryEntry(_server))
                {
                    entry.Path = "LDAP://" + member;
                    entry.Username = _domain + @"\" + _serviceAccountUsername;
                    entry.Password = _serviceAccountPassword;
                    entry.AuthenticationType = AuthenticationTypes.Secure;

                    using (DirectorySearcher searcher = new DirectorySearcher(entry))
                    {
                        searcher.Filter = "(objectClass=user)";
                        searcher.SearchScope = SearchScope.Base;

                        searcher.PropertiesToLoad.Add("mail");
                        searcher.PropertiesToLoad.Add("givenName");
                        searcher.PropertiesToLoad.Add("sn");
                        searcher.PropertiesToLoad.Add("sAMAccountName");
                        searcher.PropertiesToLoad.Add("telephoneNumber");

                        SearchResult result = searcher.FindOne();

                        if (result == null)
                            continue;

                        var dirUser = new DirectoryUser();
                        dirUser.Username = Convert.ToString(result.Properties["sAMAccountName"][0]);
                        dirUser.FirstName = Convert.ToString(result.Properties["givenName"][0]);
                        dirUser.LastName = Convert.ToString(result.Properties["sn"][0]);
                        dirUser.Email = Convert.ToString(result.Properties["mail"][0]);
                        dirUser.Phone = Convert.ToString(result.Properties["telephoneNumber"][0]);

                        directoryUsers.Add(dirUser);


                    }

                }
            }


        }
        catch { }

        return directoryUsers;

    }
迟月 2025-01-15 14:50:36

这是一种使用 DirectotyEntry 和 Microsoft LDAP_MATCHING_RULE_IN_CHAIN。我在 ActiveDirectory 2003 和 2008 R2 中使用 Framework 2.0

using System.DirectoryServices;
using System.Security.Principal;   

static void Main(string[] args) 

{ 
  //Connection to Active Directory 
  string sFromWhere = "LDAP://SRVENTR2:389/dc=societe,dc=fr"; 
  DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "societe\\administrateur", "test.2011"); 

  // To find all the users member of groups "Grp1"  : 
  // Set the base to the groups container DN; for example root DN (dc=societe,dc=fr)  
  // Set the scope to subtree 
  // Use the following filter : 
  // (member:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=X) 
  // 
  DirectorySearcher dsLookFor = new DirectorySearcher(deBase); 
  dsLookFor.Filter = "(&(memberof:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=societe,DC=fr)(objectCategory=user))"; 
  dsLookFor.SearchScope = SearchScope.Subtree; 
  dsLookFor.PropertiesToLoad.Add("cn"); 

  SearchResultCollection srcUsers = dsLookFor.FindAll(); 

  // To check user properties
  foreach (SearchResult srcUser in srcUsers) 
  { 
    Console.WriteLine("{0}", srcUser.Path); 

  } 
  Console.ReadLine(); 
}

启动 Framework 3.5 您可以使用 Directory安全主体并这样做:

/* Retreiving a principal context
 */
PrincipalContext context = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "root.123");

DirectoryContext dc = new DirectoryContext(DirectoryContextType.DirectoryServer, "WM2008R2ENT:389");
Domain dn = Domain.GetDomain(dc);
//Console.WriteLine("Le nom : {0}", dn.PdcRoleOwner.Domain);

/* Retreive a users from group
 */
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, @"MonGrpSec"))
{ 
  if (group != null)
  {
    foreach (var p in group.GetMembers(false))
    {
      Console.WriteLine(p.SamAccountName);
    } 
  } 
} 

Here is a way to do it recursively using DirectotyEntry and Microsoft LDAP_MATCHING_RULE_IN_CHAIN. I works on Framework 2.0 in an ActiveDirectory 2003 and 2008 R2

using System.DirectoryServices;
using System.Security.Principal;   

static void Main(string[] args) 

{ 
  //Connection to Active Directory 
  string sFromWhere = "LDAP://SRVENTR2:389/dc=societe,dc=fr"; 
  DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "societe\\administrateur", "test.2011"); 

  // To find all the users member of groups "Grp1"  : 
  // Set the base to the groups container DN; for example root DN (dc=societe,dc=fr)  
  // Set the scope to subtree 
  // Use the following filter : 
  // (member:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=X) 
  // 
  DirectorySearcher dsLookFor = new DirectorySearcher(deBase); 
  dsLookFor.Filter = "(&(memberof:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=societe,DC=fr)(objectCategory=user))"; 
  dsLookFor.SearchScope = SearchScope.Subtree; 
  dsLookFor.PropertiesToLoad.Add("cn"); 

  SearchResultCollection srcUsers = dsLookFor.FindAll(); 

  // To check user properties
  foreach (SearchResult srcUser in srcUsers) 
  { 
    Console.WriteLine("{0}", srcUser.Path); 

  } 
  Console.ReadLine(); 
}

Starting Framework 3.5 You can use Directory Security Principals and do it like this :

/* Retreiving a principal context
 */
PrincipalContext context = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "root.123");

DirectoryContext dc = new DirectoryContext(DirectoryContextType.DirectoryServer, "WM2008R2ENT:389");
Domain dn = Domain.GetDomain(dc);
//Console.WriteLine("Le nom : {0}", dn.PdcRoleOwner.Domain);

/* Retreive a users from group
 */
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, @"MonGrpSec"))
{ 
  if (group != null)
  {
    foreach (var p in group.GetMembers(false))
    {
      Console.WriteLine(p.SamAccountName);
    } 
  } 
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文