Active Directory Abfrage



  • Hi!!

    Ich suche schon seit einigen Tagen nach einen funktionierenden Beispiel für verschiedene Abfrage aus dem AD per C++.NET CLI.
    Ich habe nur VB Beispiele gefunden und damit kann ich gar nichts anfangen..

    Hat jemand evlt ein gutes Beispiel oder kann mir eins schreiben das wäre echt nett !

    Vielen Dank

    Gruss Osiris



  • Poste die Beispiele mal hier... das umzusetzen dürft ja einfach sein...



  • Nachtrag, hier die VB.NET Beispiele, wäre nett wenn die jemand nach C++.NET wandeln kann...

    Sub ADS_Computerkonto_anlegen()
    Dim con As DirectoryEntry
    Dim c As DirectoryEntry
    
    Const DNC = "dc=IT-Visions,dc=de"
    ' DefaultNamingContext
    Const COMPUTER_CONTAINER = "LDAP://cn=computers," _
    & DNC
    Const COMPUTER_RDN = "cn=NeuerComputer"
    Const COMPUTER_DN = "LDAP://" & COMPUTER_RDN & _
    ",cn=computers," & DNC
    
    out("# Anlegen des Computerkontos : " & COMPUTER_DN)
    
    ' --- Löschen des Computerkontos,
    ' --- wenn es bereits vorhanden ist
    If DirectoryEntry.Exists(COMPUTER_DN) Then
    out("Computerkonto ist bereits vorhanden!")
    ADSI_Loeschen_Rekursiv(COMPUTER_DN)
    End If
    
    ' --- Bindung an Computer-Container
    con = New DirectoryEntry(COMPUTER_CONTAINER)
    
    ' --- Gruppenobjekt erzeugen
    c = con.Children.Add(COMPUTER_RDN, "Computer")
    ' --- Pflichtattribute setzen
    c.Properties("SAMAccountName").Add("NEUERCOMPUTER")
    ' --- Optionale Attribute setzen
    c.Properties("Description").Add("Mein neuer Computer")
    ' --- Änderungen speichern
    c.CommitChanges()
    ' --- Ausgabe
    out("Computerkonto angelegt: " & c.Path)
    End Sub
    
    1. Create a connection to Active Directory.
    
    ''' <summary>
    ''' Method used to create an entry to the AD.
    ''' Replace the path, username, and password.
    ''' </summary>
    ''' <returns>DirectoryEntry</returns>
    Public Shared Function GetDirectoryEntry() As DirectoryEntry
    Private de As DirectoryEntry = New DirectoryEntry()
    Private de.Path = "LDAP://192.168.1.1/CN=Users;DC=Yourdomain"
    de.Username = "yourdomain\sampleuser"
    de.Password = "samplepassword"
    Return de
    End Function
    
    2. Create a secure connection to Active Directory.
    
    ''' <summary>
    ''' Method used to create an entry to the AD using a secure connection.
    ''' Replace the path.
    ''' </summary>
    ''' <returns>DirectoryEntry</returns>
    Public Shared Function GetDirectoryEntry() As DirectoryEntry
    Dim de As DirectoryEntry = New DirectoryEntry()
    Private de.Path = "LDAP://192.168.1.1/CN=Users;DC=Yourdomain"
    de.AuthenticationType = AuthenticationTypes.Secure
    Return de
    End Function
    
    ''' <summary>
    ''' Establish identity (principal) and culture for a thread.
    ''' </summary>
    Public Shared Sub SetCultureAndIdentity()
    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
    Dim principal As WindowsPrincipal = CType(Thread.CurrentPrincipal, WindowsPrincipal)
    Dim identity As WindowsIdentity = CType(principal.Identity, WindowsIdentity)
    System.Threading.Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
    End Sub
    
    3. Validate if a user exists.
    
    ''' <summary>
    ''' Method to validate if a user exists in the AD.
    ''' </summary>
    ''' <param name="UserName"></param>
    ''' <returns></returns>
    Public Function UserExists(ByVal UserName As String) As Boolean
    Dim de As DirectoryEntry = ADHelper.GetDirectoryEntry()
    Dim deSearch As DirectorySearcher = New DirectorySearcher()
    deSearch.SearchRoot =de
    deSearch.Filter = "(&(objectClass=user) (cn=" & UserName & "))"
    Dim results As SearchResultCollection = deSearch.FindAll()
    If results.Count = 0 Then
    Return False
    Else
    Return True
    End If
    End Function
    
    4. Set user's properties.
    
    ''' <summary>
    ''' Helper method that sets properties for AD users.
    ''' </summary>
    ''' <param name="de"></param>
    ''' <param name="PropertyName"></param>
    ''' <param name="PropertyValue"></param>
    Public Shared Sub SetProperty(ByVal de As DirectoryEntry, ByVal PropertyName As String, ByVal PropertyValue As String)
    If Not PropertyValue Is Nothing Then
    If de.Properties.Contains(PropertyName) Then
    de.Properties(PropertyName)(0)=PropertyValue
    Else
    de.Properties(PropertyName).Add(PropertyValue)
    End If
    End If
    
    5. Set user's country.
    
    To set the country property for a user was one of the tasks that took me some time to figure out. After some hours of research I realized that you need to know the ISO 3166 Codes for countries and set three properties to define a user's country: c, co, and countryCode.
    
    ' Set the co property using the name of the country.
    SetProperty(newuser,"co","MEXICO")
    ' Set the c property using the two-letter country code (ISO 3166 A 2).
    SetProperty(newuser,"c","MX")
    ' Set the countryCode property using the numeric value (ISO 3166 Number) of the country.
    SetProperty(newuser,"countryCode","484")
    }
    
    6. Set user's password.
    
    ''' <summary>
    ''' Method that consumes a helper class library
    ''' to generate random passwords.
    ''' </summary>
    ''' <returns></returns>
    Public Function SetSecurePassword() As String
    Dim rp As RandomPassword = New RandomPassword()
    Return rp.Generate(8,8)
    End Function
    
    ''' <summary>
    ''' Method to set a user's password
    ''' <param name="path"></param>
    Public Sub SetPassword(ByVal path As String)
    Dim usr As DirectoryEntry = New DirectoryEntry()
    usr.Path = path
    usr.AuthenticationType = AuthenticationTypes.Secure
    Dim password As Object() = New Object() {SetSecurePassword()}
    Dim ret As Object = usr.Invoke("SetPassword", password)
    usr.CommitChanges()
    usr.Close()
    End Sub
    
    ''' </summary>
    ''' Method that calls and starts SetPassword.exe
    ''' <param name="path"></param>
    ''' <param name="password"></param>
    Public Sub SetPassword(ByVal path As String, ByVal password As String)
    Dim args As StringBuilder = New StringBuilder()
    args.Append(path)
    args.Append(" ")
    args.Append(password)
    Dim startInfo As ProcessStartInfo = New ProcessStartInfo("SetPassword.exe",args.ToString())
    startInfo.WindowStyle = ProcessWindowStyle.Hidden
    Process.Start(startInfo)
    End Sub
    
    7. Enable a user account.
    
    ''' <summary>
    ''' Method to enable a user account in the AD.
    ''' </summary>
    ''' <param name="de"></param>
    Private Shared Sub EnableAccount(ByVal de As DirectoryEntry)
    'UF_DONT_EXPIRE_PASSWD 0x10000
    Dim exp As Integer = CInt(de.Properties("userAccountControl").Value)
    de.Properties("userAccountControl").Value = exp Or &H0001
    de.CommitChanges()
    'UF_ACCOUNTDISABLE 0x0002
    Dim val As Integer = CInt(de.Properties("userAccountControl").Value)
    de.Properties("userAccountControl").Value = val And Not &H0002
    de.CommitChanges()
    End Sub
    
    8. Add a user to a group.
    
    ''' <summary>
    ''' Method to add a user to a group
    ''' </summary>
    ''' <param name="de"></param>
    ''' <param name="deUser"></param>
    ''' <param name="GroupName"></param>
    Public Shared Sub AddUserToGroup(ByVal de As DirectoryEntry, ByVal deUser As DirectoryEntry, ByVal GroupName As String)
    Dim deSearch As DirectorySearcher = New DirectorySearcher()
    deSearch.SearchRoot = de
    deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
    Dim results As SearchResultCollection = deSearch.FindAll()
    Dim isGroupMember As Boolean = False
    If results.Count>0 Then
    Dim group As DirectoryEntry = GetDirectoryEntry(results(0).Path)
    Dim members As Object = group.Invoke("Members",Nothing)
    For Each member As Object In CType(members, IEnumerable)
    Dim x As DirectoryEntry = New DirectoryEntry(member)
    Dim name As String = x.Name
    If name <> deUser.Name Then
    isGroupMember = False
    Else
    isGroupMember = True
    Exit For
    End If
    Next member
    If (Not isGroupMember) Then
    group.Invoke("Add", New Object() {deUser.Path.ToString()})
    End If
    group.Close()
    End If
    Return
    End Sub
    
    9. Generate a mailbox for a user in Microsoft Exchange Server.
    
    ''' <summary>
    ''' Method that calls and starts a WSHControl.vbs
    ''' </summary>
    ''' <param name="userAlias"></param>
    Public Sub GenerateMailBox(ByVal userAlias As String)
    Dim mailargs As StringBuilder = New StringBuilder()
    mailargs.Append("WSHControl.vbs")
    mailargs.Append(" ")
    mailargs.Append(userAlias)
    Dim sInfo As ProcessStartInfo = New ProcessStartInfo("Wscript.exe",mailargs.ToString())sInfo.WindowStyle = ProcessWindowStyle.Hidden
    Process.Start(sInfo)
    End Sub
    
    10. Create a user account.
    
    ''' <summary>
    ''' Method that creates a new user account
    ''' </summary>
    ''' <param name="employeeID"></param>
    ''' <param name="name"></param>
    ''' <param name="login"></param>
    ''' <param name="email"></param>
    ''' <param name="group"></param>
    Public Sub CreateNewUser(ByVal employeeID As String, ByVal name As String, ByVal login As String, ByVal email As String, ByVal group As String)
    Dim catalog As Catalog = New Catalog()
    Dim de As DirectoryEntry = ADHelper.GetDirectoryEntry()
    ''' 1. Create user account
    Dim users As DirectoryEntries = de.Children
    Dim newuser As DirectoryEntry = users.Add("CN=" & login, "user")
    ''' 2. Set properties
    SetProperty(newuser,"employeeID", employeeID)
    SetProperty(newuser,"givenname", name)
    SetProperty(newuser,"SAMAccountName", login)
    SetProperty(newuser,"userPrincipalName", login)
    SetProperty(newuser,"mail", email)
    newuser.CommitChanges()
    ''' 3. Set password
    SetPassword(newuser.Path)
    newuser.CommitChanges()
    ''' 4. Enable account
    EnableAccount(newuser)
    ''' 5. Add user account to groups
    AddUserToGroup(de,newuser,group)
    ''' 6. Create a mailbox in Microsoft Exchange
    GenerateMailBox(login)
    newuser.Close()
    de.Close()
    End Sub
    
    11. Disable a user account.
    
    ''' <summary>
    ''' Method that disables a user account in the AD and hides user's email from Exchange address lists.
    ''' </summary>
    ''' <param name="EmployeeID"></param>
    Public Sub DisableAccount(ByVal EmployeeID As String)
    Dim de As DirectoryEntry = GetDirectoryEntry()
    Dim ds As DirectorySearcher = New DirectorySearcher(de)
    ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" & EmployeeID & "))"
    ds.SearchScope = SearchScope.Subtree
    Dim results As SearchResult = ds.FindOne()
    If Not results Is Nothing Then
    Dim dey As DirectoryEntry = GetDirectoryEntry(results.Path)
    Dim val As Integer = CInt(dey.Properties("userAccountControl").Value)
    dey.Properties("userAccountControl").Value = val Or &H0002
    dey.Properties("msExchHideFromAddressLists").Value = "TRUE"
    dey.CommitChanges()
    dey.Close()
    End If
    de.Close()
    End Sub
    
    12. Update user account.
    
    ''' <summary>
    ''' Method that updates user's properties
    ''' </summary>
    ''' <param name="employeeID"></param>
    ''' <param name="department"></param>
    ''' <param name="title"></param>
    ''' <param name="company"></param>
    Public Sub ModifyUser(ByVal employeeID As String, ByVal department As String, ByVal title As String, ByVal company As String)
    Dim de As DirectoryEntry = GetDirectoryEntry()
    Dim ds As DirectorySearcher = New DirectorySearcher(de)
    ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" & employeeID & "))"
    ds.SearchScope = SearchScope.Subtree
    Dim results As SearchResult = ds.FindOne()
    If Not results Is Nothing Then
    Dim dey As DirectoryEntry = GetDirectoryEntry(results.Path)
    SetProperty(dey, "department", department)
    SetProperty(dey, "title", title)
    SetProperty(dey, "company", company)
    dey.CommitChanges()
    dey.Close()
    End If
    de.Close()
    End Sub
    
    13. Validate if a string has a correct email pattern.
    
    ''' <summary>
    ''' Method that validates if a string has an email pattern.
    ''' </summary>
    ''' <param name="mail"></param>
    ''' <returns></returns>
    Public Function IsEmail(ByVal mail As String) As Boolean
    Dim mailPattern As Regex = New Regex("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
    Return mailPattern.IsMatch(mail)
    End Function
    
    14. Extract a user alias from an email account.
    
    ''' <summary>
    ''' Method to extract the alias from an email account.
    ''' dada una cuenta de correo electrónico
    ''' </summary>
    ''' <param name="mailAddress"></param>
    ''' <returns></returns>
    Public Function GetAlias(ByVal mailAddress As String) As String
    If IsEmail(mailAddress) Then
    Return mailAddress.Substring(0,mailAddress.IndexOf("@"))
    Else
    Return " "
    End If
    End Function
    
    15. Format dates to AD date format (AAAAMMDDMMSSSS.0Z).
    
    ''' <summary>
    ''' Method that formats a date in the required format
    ''' needed (AAAAMMDDMMSSSS.0Z) to compare dates in AD.
    ''' </summary>
    ''' <param name="date"></param>
    ''' <returns>Date in valid format for AD</returns>
    Public Function ToADDateString(ByVal date_Renamed As DateTime) As String
    Dim year As String = date_Renamed.Year.ToString()
    Dim month As Integer = date_Renamed.Month
    Dim day As Integer = date_Renamed.Day
    Dim sb As StringBuilder = New StringBuilder()
    sb.Append(year)
    If month <10 Then
    sb.Append("0")
    End If
    sb.Append(month.ToString())
    If day <10 Then
    sb.Append("0")
    End If
    sb.Append(day.ToString())
    sb.Append("000000.0Z")
    Return sb.ToString()
    End Function
    
    16. Search users.
    
    ''' <summary>
    ''' Method that returns a DataTable with a list of users modified from a given date.
    ''' </summary>
    ''' <param name="fromdate"></param>
    Public Function GetModifiedUsers(ByVal fromdate As DateTime) As DataTable
    Dim dt As DataTable = New DataTable()
    dt.Columns.Add("EmployeeID")
    dt.Columns.Add("Name")
    dt.Columns.Add("Email")
    Dim de As DirectoryEntry = GetDirectoryEntry()
    Dim ds As DirectorySearcher = New DirectorySearcher(de)
    Dim filter As StringBuilder = New StringBuilder()
    filter.Append("(&(objectCategory=Person)(objectClass=user)(whenChanged>=")filter.Append(date.ToADDateString())
    filter.Append("))")
    ds.Filter=filter.ToString()
    ds.SearchScope = SearchScope.Subtree
    Dim results As SearchResultCollection= ds.FindAll()
    For Each result As SearchResult In results
    Dim dr As DataRow = dt.NewRow()
    Dim dey As DirectoryEntry = GetDirectoryEntry(result.Path)
    dr("EmployeeID") = dey.Properties("employeeID").Value
    dr("Name") = dey.Properties("givenname").Value
    dr("Email") = dey.Properties("mail").Value
    dt.Rows.Add(dr)
    dey.Close()
    Next result
    de.Close()
    Return dt
    End Function
    


  • Fang einfach mal hier an:
    http://msdn2.microsoft.com/de-de/library/system.directoryservices.directoryentry(VS.80).aspx

    z.B.

    Public Shared Function GetDirectoryEntry() As DirectoryEntry
    Private de As DirectoryEntry = New DirectoryEntry()
    Private de.Path = "LDAP://192.168.1.1/CN=Users;DC=Yourdomain"
    de.Username = "yourdomain\sampleuser"
    de.Password = "samplepassword"
    Return de
    End Function
    

    ergibt in C++/CLI:

    DirectoryEntry^ GetDirectoryEntry()
    {
      DirectoryEntry^ de = gcnew DirectoryEntry();
      de.Path = "LDAP://192.168.1.1/CN=Users;DC=Yourdomain";
      de.Username = "yourdomain\\sampleuser";
      de.Password = "samplepassword";
      return de;
    }
    

Anmelden zum Antworten