C# (CSharp, C-Sharp) Windows Active Directory last logon

January 7, 2017

Hi guys

Please note, many threads were referred in order to compile the script attached below & all I did was re-arranging in order for better reading/formatting

(And I insure that the script works under following scenarios:

  1. You are a domain administrator
  2. You are administrating Windows 2003 onwards Windows domain
  3. Your puter is connected to the domain network ;)

)

Referenced websites/threads

  1. http://stackoverflow.com/questions/15775264/searching-for-lastlogon-attribute-of-user-in-multiple-domain-servers
  2. https://www.codeproject.com/kb/security/lastlogonacrossallwindows.aspx#_comments
  3. http://codebeautify.org/csharpviewer (for formatting the C# code)

How to test the code

Start Visual Studio (I am using 2013 Professional edition, you can use any of the community editions to test the scripts)

Create a new C# Console Application and name it llogon (else you need to change the namespace name “llogon” according to the name you have chosen for your new project.

Add the following references to your project

  1. “Framework -> System.DirectoryServices”
  2. “Browse and add -> C:\Windows\System32\activeds.tlb”

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//Added by Rajesh

//using System.Management;
//using System.Data;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
//http://stackoverflow.com/questions/33274162/the-namespace-of-iadslargeinteger
//ActiveDS namespace
using ActiveDs; // Namespace added via ref to C:\Windows\System32\activeds.tlb
//https://www.codeproject.com/kb/security/lastlogonacrossallwindows.aspx

namespace llogon
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the root entry
            DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
            string configurationNamingContext =
             (string)rootDSE.Properties["configurationNamingContext"].Value;
            string defaultNamingContext =
             (string)rootDSE.Properties["defaultNamingContext"].Value;
            Dictionary<string, Int64> lastLogons = new Dictionary<string, Int64>();
            // Get all the domain controllers
            DirectoryEntry deConfig = new DirectoryEntry("LDAP://" + configurationNamingContext);
            DirectorySearcher dsConfig = new DirectorySearcher(deConfig);
            dsConfig.Filter = "(objectClass=nTDSDSA)";
            foreach (SearchResult srDomains in dsConfig.FindAll())
            {
                DirectoryEntry deDomain = srDomains.GetDirectoryEntry();
                if (deDomain != null)
                {
                    string dnsHostName =
                     deDomain.Parent.Properties["DNSHostName"].Value.ToString();
                    // Get all the users for that domain
                                   DirectoryEntry deUsers =
                     new DirectoryEntry("LDAP://" + dnsHostName + "/" + defaultNamingContext);
                    DirectorySearcher dsUsers = new DirectorySearcher(deUsers);
                    dsUsers.Filter = "(&(objectCategory=person)(objectClass=user))";
                    foreach (SearchResult srUsers in dsUsers.FindAll())
                    {
                        DirectoryEntry deUser = srUsers.GetDirectoryEntry();
                        if (deUser != null)
                        {
                            // Get the distinguishedName and lastLogon for each user
                            // Save the most recent logon for each user in a Dictionary object
                            string distinguishedName = deUser.Properties["distinguishedName"].Value.ToString();
                            Int64 lastLogonThisServer = new Int64();
                            if (deUser.Properties["lastLogon"].Value != null)
                            {
                                IADsLargeInteger lgInt =
                                 (IADsLargeInteger)deUser.Properties["lastLogon"].Value;
                                lastLogonThisServer = ((long)lgInt.HighPart << 32) + lgInt.LowPart;
                            }

                            // Save the most recent logon for each user in a Dictionary object
                            if (lastLogons.ContainsKey(distinguishedName))
                            {
                                if (lastLogons[distinguishedName] < lastLogonThisServer)
                                {
                                    lastLogons[distinguishedName] = lastLogonThisServer;
                                }
                            }
                            else
                            {
                                lastLogons.Add(distinguishedName, lastLogonThisServer);
                            }
                            string readableLastLogon = DateTime.FromFileTime(lastLogonThisServer).ToString();
                            Console.WriteLine("User: " + distinguishedName + "Last logon: " +readableLastLogon);
                        }
                    }
                    Console.ReadLine();
                }
            }

        }
    }
}

Try the code & if you are stuck somewhere, do let me through the comments. I am working on a WPF C# project for a simple Active Directory Reporter / Asset Management System using WMI. Stay tuned & I will soon post the entire solution here :)

regards,

rajesh

 


VB.Net | Active Directory | Windows Form Application for listing users & details in a grid view

January 15, 2015

Have you read our previous post about finding last logon date time value for a domain member computer or user yet? If not, please read about it here

Now, we are going to provide you a decent (Warning: Amateurish code blocks possible) Windows forms based application that could list all your domain users and few of their details including last logon date time values.

run

Above image demonstrates the run time interface of the application. Application has a search textbox, that could accept values before and after the user details are populated.

Before the population, the users will be limited to matching string, after population, the list could be refined against the combination of keystrokes

Mandatory References as seen with the below image

ref

You can download the solution from here

regards,

rajesh


Oracle 10g | Get Windows User Details from Active Directory

December 9, 2014

Hello guys! 9th December 2014 : Minor update The following exercise will not materialize if you have a middleware sever, as the client information will not be available for your forms. Missed us? :) Recently we were challenged with a very interesting task, and that was to send emails to the requester of a particular activity once after the completion. Usually, we can look into the HR/Payroll enrollments and get the email address for the user without much troubles. Our case was different, our HR/Payroll records are not always up to date and we were forced to capture the Windows login name and get the email addresses straight away from the AD database! As usual, after hours of googling and trying out few scripts, We came up with a tailored script that fetches us the full Name and email address against value derived from

Select sys_context('userenv','os_user') from dual;

query Here, we are sharing the scripts with you Complete credits go to the following few & many others http://www.dba-oracle.com/t_packages_dbms_ldap.htm http://oracle-base.com/articles/9i/ldap-from-plsql-9i.php (Our script is a complete rip-off from oracle-base.com article)

/* Formatted on 12/9/2014 2:56:10 PM (QP5 v5.163.1008.3004) */
SET SERVEROUTPUT ON SIZE UNLIMITED;
 
DECLARE
   /*This block commented never worked for us
      -- Adjust as necessary.
      --   l_ldap_host    VARCHAR2(256) := 'server01.tshcomputing.com';
      --  l_ldap_port    VARCHAR2(256) := '389';
      --  l_ldap_user    VARCHAR2(256) := 'cn=orcladmin';
      --  l_ldap_passwd  VARCHAR2(256) := 'password';
      --  l_ldap_base    VARCHAR2(256) := 'cn=Users,dc=tshcomputing,dc=com';
   */
 
 
   --Active Directory Component Windows 2008 R2
 
   l_ldap_host     VARCHAR2 (256)
                      := 'fully qualitifed name of your domain controller'; --eg (abc-efg@xyz.com)
   l_ldap_port     VARCHAR2 (256) := '389';
   l_ldap_user     VARCHAR2 (256) := 'fully qualified user name'; --eg: paul@xyz.com (make sure paul is a member of Administrators group)
   l_ldap_passwd   VARCHAR2 (256) := 'password'; -- clear text password for user paul@kazema.com
   l_ldap_base     VARCHAR2 (256) := 'DC=xyz,DC=com';
   -- l_ldap_base     VARCHAR2 (256) := 'OU=GEN Managers,DC=xyz,DC=com'; --Restrict the query to a particular OU within AD
   --AD 2008 R2
 
 
 
   l_retval        PLS_INTEGER;
 
   l_session       DBMS_LDAP.session;
   l_attrs         DBMS_LDAP.string_collection;
   l_message       DBMS_LDAP.MESSAGE;
   l_entry         DBMS_LDAP.MESSAGE;
   l_attr_name     VARCHAR2 (256);
   l_ber_element   DBMS_LDAP.ber_element;
   l_vals          DBMS_LDAP.string_collection;
BEGIN
   -- Choose to raise exceptions.
   DBMS_LDAP.USE_EXCEPTION := TRUE;
 
   -- Connect to the LDAP server.
   l_session := DBMS_LDAP.init (hostname => l_ldap_host, portnum => l_ldap_port);
 
   l_retval :=
      DBMS_LDAP.simple_bind_s (ld       => l_session,
                               dn       => l_ldap_user,
                               passwd   => l_ldap_passwd);
 
 
   -- l_attrs(1) := '*'; -- Get all attributes(Complete AD details will be read, use carefully)
 
   l_attrs (1) := 'mail';
   l_attrs (2) := 'displayName';
 
   --Common Attributes you can pass to the AD query
   --  l_attrs(1)  := 'sAMAccountName';
   --   l_attrs(2)  := 'employeeNumber';
   --    l_attrs(3)  := 'displayName';
   --    l_attrs(4)  := 'description';
   --    l_attrs(5)  := 'telephoneNumber';
   --    l_attrs(6)  := 'facsimileTelephoneNumber';
   --   l_attrs(7)  := 'department';
   --   l_attrs(8)  := 'company';
   --    l_attrs(9)  := 'employeeID';
   --   l_attrs(10) := 'streetAddress';
   --   l_attrs(11) := 'mail';
   --   l_attrs(12) := 'c';
   --  l_attrs(13) := 'l';
   --   l_attrs(14) := 'postalCode';
 
 
   -- retrieve all attributes
   l_retval :=
      DBMS_LDAP.search_s (ld         => l_session,
                          base       => l_ldap_base,
                          scope      => DBMS_LDAP.SCOPE_SUBTREE,
                          --          filter   => 'objectclass=*', --All the objects will be read
                          filter     => 'sAMAccountName=paul', --Record for User with windows login account as &quot;Paul&quot; will be fetched
                          attrs      => l_attrs,
                          attronly   => 0,
                          res        => l_message);
 
   IF DBMS_LDAP.count_entries (ld => l_session, msg => l_message) > 0
   THEN
      -- Get all the entries returned by our search.
      l_entry := DBMS_LDAP.first_entry (ld => l_session, msg => l_message);
 
     <<entry_loop>>
      WHILE l_entry IS NOT NULL
      LOOP
         -- Get all the attributes for this entry.
         DBMS_OUTPUT.PUT_LINE ('---------------------------------------');
         l_attr_name :=
            DBMS_LDAP.first_attribute (ld          => l_session,
                                       ldapentry   => l_entry,
                                       ber_elem    => l_ber_element);
 
        <<attributes_loop>>
         WHILE l_attr_name IS NOT NULL
         LOOP
            -- Get all the values for this attribute.
            l_vals :=
               DBMS_LDAP.get_values (ld          => l_session,
                                     ldapentry   => l_entry,
                                     attr        => l_attr_name);
 
           <<values_loop>>
            FOR i IN l_vals.FIRST .. l_vals.LAST
            LOOP
               DBMS_OUTPUT.PUT_LINE (
                     'ATTIBUTE_NAME: '
                  || l_attr_name
                  || ' = '
                  || SUBSTR (l_vals (i), 1, 200));
            END LOOP values_loop;
 
            l_attr_name :=
               DBMS_LDAP.next_attribute (ld          => l_session,
                                         ldapentry   => l_entry,
                                         ber_elem    => l_ber_element);
         END LOOP attibutes_loop;
 
         l_entry := DBMS_LDAP.next_entry (ld => l_session, msg => l_entry);
      END LOOP entry_loop;
   END IF;
 
   -- Disconnect from the LDAP server.
   l_retval := DBMS_LDAP.unbind_s (ld => l_session);
   DBMS_OUTPUT.PUT_LINE ('L_RETVAL: ' || l_retval);
END;
/

Try it & let us know the experiences! regards,