V
V
Vladimir Yurchenkov2021-05-27 18:34:03
LDAP
Vladimir Yurchenkov, 2021-05-27 18:34:03

How to get the memberOf list of an AD group?

Hello. I'm trying to get a memberOf list of a specific group.

For example, there is a group, I need to pull out this list:

60afb3e273059614871801.jpeg

I'm looking for groups and their attributes (for example, name, description) without any problems. When it comes to pull memberOf into a list, nothing happens.

Now I'm trying to pull out through this method.

public ArrayList AttributeValuesMultiString(string attributeName,
     string objectDn, ArrayList valuesCollection, bool recursive)
{
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    PropertyValueCollection ValueCollection = ent.Properties[attributeName];
    IEnumerator en = ValueCollection.GetEnumerator();

    while (en.MoveNext())
    {
        if (en.Current != null)
        {
            if (!valuesCollection.Contains(en.Current.ToString()))
            {
                valuesCollection.Add(en.Current.ToString());
                if (recursive)
                {
                    AttributeValuesMultiString(attributeName, "LDAP://" +
                    en.Current.ToString(), valuesCollection, true);
                }
            }
        }
    }
    ent.Close();
    ent.Dispose();
    return valuesCollection;
}


At the output, I transfer ArrayList to ListView, at least 1 element so far:

foreach(string str in glist) 
{
var items = new ListViewItem();
items.Text = str;
MyListView.Items.Add(items);
}


But I get nothing, no errors.

PS I tried that, it didn't work at all

Источник
// Описываем функцию формирования подгрупп
        private List<string> ADGrouppList(string ADGroupp)
        {
            // Объявляем список для хранения полных имен групп
            List<string> ADGrouppM = new List<string>();
            // Указываем домен для поиска
            string deConnectionString = "LDAP://DC=msk,DC=aeroflot,DC=ru";
            // Защита от ошибок
            try
            {
                using (var entry = new DirectoryEntry(deConnectionString))
                using (var search = new DirectorySearcher(entry))
                {
                    string query = string.Format("(&(objectClass=group){0})", ADGroupp); // Описываем фильтр
                    search.Filter = query;
                    search.PropertiesToLoad.Add("Name"); // Имена групп
                    search.PropertiesToLoad.Add("adspath"); // LDAP-путь к группе
                    search.PropertiesToLoad.Add("memberof"); // Членство в группе
                    // Ищем все группы с именем из переменной ADGroupp
                    using (var mySearchResultColl = search.FindAll())
                        if (mySearchResultColl.Count > 0) // Если находим хотя бы одну
                        {
                            string SAD = ""; 
                            foreach (SearchResult ADResult in mySearchResultColl)
                            {
                                foreach (object property in ADResult.Properties["adspath"])
                                    SAD = property.ToString();
                                if (SAD == "LDAP://CN=Domain Admins,CN=Users,DC=msk,DC=aeroflot,DC=ru")
                                    MessageBox.Show("Domain admins","Exception");
                                ADGrouppM.Add("(memberof=CN=" + SAD.Substring(10,
                                    SAD.Length - 10) + ")"); // Обрезаем первые 10 символов                                
                                ADGrouppM.AddRange(ADGrouppList("(memberof=CN=" + SAD.Substring(10,
                                    SAD.Length - 10) + ")")); // Добавляем подгруппы подгруппы подгруппы ...
                                
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            return ADGrouppM;
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Yurchenkov, 2021-06-03
@EPIDEMIASH

In general, I answer my own question:
We get information about the group in AD

var ctd = new PrincipalContext(ContextType.Domain); // Получаем текущий домен
string Group = data; // Задаем имя группы для поиска (у меня тянет data из другой формы)
var getGR = GroupPrincipal.FindByIdentity(ctd, Group); // Ищем нашу группу и атрибуты

// Выводим имя и описание
lg_name.Text = getGR.SamAccountName;
lg_desc.Text = getGR.Description;

Next, in my case, I need to get the "Member of Groups" tab
int sumGroups = 0;

PrincipalSearchResult<Principal> g = getGR.GetGroups();
foreach (var usr in g)
{
this.listGroup.Items.Add(usr.SamAccountName); // Вывожу перебором все найденные подгруппы в список
sumGroups++;
}

If you need users "Group Members", then accordingly:
PrincipalSearchResult<Principal> g = getGR.GetMembers()

R
Roman Bezrukov, 2021-05-28
@NortheR73

They claim that this method works ...
PS I did not check it myself, because for such purposes I use more PowerShell

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question