Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically find out the last login time to a machine?

I would like to a) programatically and b) remotely find out the last date/time that a user successfully logged into a Windows machine (via remote desktop or at the console). I would be willing to take any typical windows language (C, C#, VB, batch files, JScript, etc...) but any solution would be nice.

like image 956
esac Avatar asked Dec 23 '22 08:12

esac


2 Answers

Try this:

  public static DateTime? GetLastLogin(string domainName,string userName)
  {
        PrincipalContext c = new PrincipalContext(ContextType.Domain,domainName);
        UserPrincipal uc = UserPrincipal.FindByIdentity(c, userName);
        return uc.LastLogon;
   }

You will need to add references to using using System.DirectoryServices and System.DirectoryServices.AccountManagement

EDIT: You might be able to get the last login Datetime to a specific machine by doing something like this:

 public static DateTime? GetLastLoginToMachine(string machineName, string userName)
 {
        PrincipalContext c = new PrincipalContext(ContextType.Machine, machineName);
        UserPrincipal uc = UserPrincipal.FindByIdentity(c, userName);
        return uc.LastLogon;

 }
like image 121
Abhijeet Patel Avatar answered Dec 24 '22 22:12

Abhijeet Patel


You can use DirectoryServices to do this in C#:

using System.DirectoryServices;

        DirectoryEntry dirs = new DirectoryEntry("WinNT://" + Environment.MachineName);
        foreach (DirectoryEntry de in dirs.Children)
        {
            if (de.SchemaClassName == "User")
            {
                Console.WriteLine(de.Name);
                if (de.Properties["lastlogin"].Value != null)
                {
                    Console.WriteLine(de.Properties["lastlogin"].Value.ToString());
                }
                if (de.Properties["lastlogoff"].Value != null)
                {
                    Console.WriteLine(de.Properties["lastlogoff"].Value.ToString());
                }
            }
        }
like image 20
Kolten Avatar answered Dec 24 '22 22:12

Kolten