- How to prevent the name of the last logged-on user from being displayed in the Log On to Windows dialog box in Windows Server 2003
- Summary
- Resolution
- Troubleshooting
- References
- Last logon time of user
- Получаем логи (историю) входа пользователя в домен AD
- Политика аудита входа пользователя в домен
- PowerShell: истории сетевых входов пользователя в домен
- Получаем информацию об активности пользователя в домене по событиям Kerberos
How to prevent the name of the last logged-on user from being displayed in the Log On to Windows dialog box in Windows Server 2003
This article describes how to prevent the name of the last logged-on user from being displayed in the Log On to Windows dialog box.
Original product version: В Windows 10 — all editions, Windows Server 2012 R2
Original KB number: В 324740
Summary
By default, Windows displays the name of the last user who successfully logged on to the computer. This name is displayed in the Log On to Windows dialog box. Security administrators may prefer that the last logged-on user name not be displayed in the Log On to Windows dialog box. Although this configuration requires that users must type their user name (and password) each time that they sign in, it can help to prevent attempts by unauthorized users to gain access to the computer.
You can use Group Policy to prevent the name of the last logged-on user from being displayed in the Log On to Windows dialog box. The group policy can apply to the local computer, sites, domains, and organizational units (OU).
Resolution
- Select Start, select Run, type mmc in the Open box, and then select OK.
- On the File menu, select Add/Remove Snap-in.
- Select Add.
- Select Group Policy Object Editor, and then select Add.
- Select the target Group Policy object (GPO). The default GPO is Local Computer. Click Browse to select the GPO that you want, and then select Finish.
- Select Close, and then select OK.
- Expand the group policy object, expand Computer Configuration, expand Windows Settings, and then expand Security Settings.
- Expand Local Policies, and then select Security Options.
- In the right pane, double-click Interactive logon: Do not display last user name.
- Click to select the Define this policy setting check box (if it’s present), and then select Enabled.
- Select OK.
Troubleshooting
Microsoft Windows NT 4.0-based computers don’t support Windows Server 2003 Group Policy.
References
For more information about working with Group Policy in Windows Server 2003, see Group Policy Help. To do it, select Help on the Action menu in the Group Policy Object Editor snap-in, select the Contents tab, and then select Group Policy.
Last logon time of user
Using ‘Net user’ command we can find the last login time of a user. The exact command is given below.
Example:
To find the last login time of the computer administrator
For a domain user, the command would be as below.
How to find the last user logged into the machine?
IS there any way to find this from command line?
function Get-ADUserLastLogon([string]$userName)
<
$dcs = Get-ADDomainController -Filter
$time = 0
foreach($dc in $dcs)
<
$hostname = $dc.HostName
$user = Get-ADUser $userName | Get-ADObject -Properties lastLogon
if($user.LastLogon -gt $time)
<
$time = $user.LastLogon
>
>
$dt = [DateTime]::FromFileTime($time)
Write-Host $username “last logged on at:” $dt >
Get-ADUserLastLogon -UserName XXXXX
I think from event log we can find the last logged in user name. I do not know of any way to know this from command line.
I run CMD with Admin right. But I receive MSG: “FINDSTR: Can not open logon”?
May you explain me?
I think you have executed something like below
net user administrator | findstr /B /C:Last logon
You may have missed double quotes around ‘Last Logon’. Run the command “net user administrator | findstr /B /C:”Last logon”. It would print the last login time.
what command to use if we want to see last 5 logons ??
You can also see it by typing this in cmd (Command Prompt):
net user(press enter key)
then again type
net user xxx
xxx- name of username you obtained from first command of net user
I think net user xxx will only show the last time the user “logged on”, which will not be reflected in a restart of Windows if you have the account set to not require a password logon initially. This date and time will only be accurate if the user had to actually put in a password and “log on”.
I think a better alternative is
This will show the date and time the user account logged on, and will reflect any restart of Windows that bypassed the login process.
C:>quser Jeffrey
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>jeffrey console 2 Active none 1/16/2016 11:20 AM
How can I use this to show more than one value. In example if may wanted to show User name and Password last set. Thanks!
Is there a way to run this command on an OU in AD so that I could export a list of users in said OU with their last log on dates?
‘net’ is not recognized as an internal or extarnal command,operable program or batch file
this is occur what can i do for it..
Is there a way in CMD to get last 3
6 user logon with date & time or duration & save it in text file. I have a hard time to find a culprit student who love to sabotage my labs keyboard button.
QUser cblackburn was what I needed thank you. Is there a different command that will show me the last time I locked or unlocked the machine which would still be more recent. I know this is in the event viewer, but it’s a mess.
Works perfectly for local users on Server 2008 R2
what command to use if we want to see last 10 logons ??
How can one find the last time a user logged into a machine?
IS there any way to find this from command line?
kumar’s answer does not work for A user, on A machine. It provides when the user logged into some computer on the domain.
This only works for local accounts.
which command ?? to see which last user has used the following machine xxx.
this needs to be updated for Windows 10, since users often logon with PIN or face. There should be another different cmd to display the last “logon” from that. People don’t typically logon with a password any more. It’s mostly with PIN or face.
For 1809 and upper builds this solution not work 100%
CMD was return nothing.
How can change the cmd to obtain this for all local users at once.
So I would not have to retype this cmd for every single user.
Получаем логи (историю) входа пользователя в домен AD
Есть несколько различных инструментов получения информации о времени логина пользователя в домен. Время последней успешной аутентификации пользователя в домене можно получить из атрибута lastLogon (обновляется только на контроллере домена, на котором выполнена проверка учетных данных пользователя) или lastLogonTimpestamp (реплицируется между DC в домене, но по умолчанию только через 14 дней). Вы можете получить значение этого атрибута пользователя в редакторе атрибутов AD или командлетом Get-ADUser. Однако иногда нужно получить историю активности (входов) пользователя в домене за большой период времени.
Вы можете получить информацию об успешных входах (аутентфикации) пользователя в домене из журналов контроллеров домена. В этой статье мы покажем, как отслеживать историю входов пользователя в домен с помощью PowerShell.. Т.е. можно получить полную историю активности пользователя в домене, время начала работы и компьютеры, с которых работает пользователь.
Политика аудита входа пользователя в домен
Чтобы в журналах контроллеров домена отображалась информация об успешном/неуспешном входе в систему, нужно включить политику аудита событий входа пользователей.
- Запустите редактор доменных GPO – GPMC.msc;
- Откройте настройки Default Domain Policy и перейдите в раздел Computer Configuration -> Policies -> Windows Settings -> Security Settings –> Advanced Audit Policy Configuration -> Audit Policies -> Logon/Logoff;
Audit Policies -> Logon/Logoff» width=»692″ height=»371″ srcset=»https://winitpro.ru/wp-content/uploads/2020/04/advanced-audit-policy-configuration-greater-audit-polic.png 943w, https://winitpro.ru/wp-content/uploads/2020/04/advanced-audit-policy-configuration-greater-audit-polic-300×161.png 300w, https://winitpro.ru/wp-content/uploads/2020/04/advanced-audit-policy-configuration-greater-audit-polic-768×411.png 768w» sizes=»(max-width: 692px) 100vw, 692px»/>
- Включите две политики аудита (Audit Logon и Audit Other Logon/Logoff Events). Чтобы в журналах Security на DC и компьютерах регистрировались как успешные, так и неуспешные политики входа, выберите в настройках политика аудита опции Success и Failure
- Сохраните изменения в GPO и обновите настройки политик на контроллерах домена командой: gpupdate /force (или подождите 90 минут, без учета репликации между DC).
Теперь при входе пользователя на любой компьютер домена Active Directory в журнале контроллера домена, который выполняет аутентификацию пользователя, появляется событие с Event ID 4624 (An account was successfully logged on). В описании этого события указана учетная запись, которая успешно аутентифицировалась (Account name), имя (Workstation name) или IP адрес (Source Network Address) компьютера, с которого выполнен вход.
Также в поле Logon Type указан тип входа в систему. Нас интересуют следующие коды
- Logon Type 10 – Remote Interactive logon – вход через службы RDP, теневое подключение или Remote Assistance (на DC такое событие может быть при входе администратора, или другого пользователя, которому предоставлены права входа на DC) Это событие используется при анализе событий входа пользователей по RDP.
- Logon Type 3 – Network logon сетевой вход (происходит при аутентфикации пользователя на DC, подключения к сетевой папке, принтеру или службе IIS)
Также можно отслеживать событие выдачи билета Kerberos при аутентификации пользователя. Event ID 4768 — A Kerberos authentication ticket (TGT) was requested. Для этого нужно включить аудит событий в политики Account Logon –> Audit Kerberos Authentication Service -> Success и Failure.
В событии 4768 также указана учетная запись пользователя (Account Name или User ID), который получил билет Kerberos (аутентифицировался) и имя (IP адрес) компьютера.
PowerShell: истории сетевых входов пользователя в домен
С помощью командлета PowerShell Get-Eventlog можно получить все события из журнала контроллера домена, отфильтровать их по нужному коду (EventID) и вывести данные о времени, когда пользователь аутентифицировался в домене, и компьютере, с которого выполнен вход. Т.к. в домене может быть несколько контроллеров домена и нужно получить история входов пользователя с каждого из них, нужно воспользоваться командлетом Get-ADDomainController (из модуля AD для Windows PowerShell). Данный командлет позволяет получить список всех DC в домене.
Следующий PowerShell скрипт позволяет получить все события входа пользователя в домен AD со всех контроллеров домена. На выходе вы получаете таблицу с историей входа пользователя и компьютеров, с которых аутентифицировался пользователь.
# имя пользователя, историю входов которого нужно получить
$checkuser=’*ivanov*’
# получаем информацию об истории входов пользователя за последних 2 дня, можете изменить
$startDate = (get-date).AddDays(-2)
$DCs = Get-ADDomainController -Filter *
foreach ($DC in $DCs)<
$logonevents = Get-Eventlog -LogName Security -InstanceID 4624 -after $startDate -ComputerName $dc.HostName
foreach ($event in $logonevents)<
if (($event.ReplacementStrings[5] -notlike ‘*$’) -and ($event.ReplacementStrings[5] -like $checkuser)) <
# Remote (Logon Type 10)
if ($event.ReplacementStrings[8] -eq 10)<
write-host «Type 10: Remote Logon`tDate: «$event.TimeGenerated «`tStatus: Success`tUser: «$event.ReplacementStrings[5] «`tWorkstation: «$event.ReplacementStrings[11] «`tIP Address: «$event.ReplacementStrings[18] «`tDC Name: » $dc.Name
>
# Network(Logon Type 3)
if ($event.ReplacementStrings[8] -eq 3)<
write-host «Type 3: Network Logon`tDate: «$event.TimeGenerated «`tStatus: Success`tUser: «$event.ReplacementStrings[5] «`tWorkstation: «$event.ReplacementStrings[11] «`tIP Address: «$event.ReplacementStrings[18] «`tDC Name: » $dc.Name
>
>
>
>
Получаем информацию об активности пользователя в домене по событиям Kerberos
Также вы можете получить историю аутентификации пользователя в домене по по событию выдачи билета Kerberos (TGT Request — EventID 4768). В этом случае в итоговых данных будет содержаться меньшее количество событий (исключены сетевые входы, обращения к папкам на DC во время получения политик и выполнения логон-скриптов). Следующий PowerShell скрипт выведет информацию о всех входах пользователей за последние 24 часа:
$alluserhistory = @()
$startDate = (get-date).AddDays(-2)
$DCs = Get-ADDomainController -Filter *
foreach ($DC in $DCs)<
$logonevents = Get-Eventlog -LogName Security -InstanceID 4768 -after $startDate -ComputerName $dc.HostName
foreach ($event in $logonevents)<
if ($event.ReplacementStrings[0] -notlike ‘*$’) <
$userhistory = New-Object PSObject -Property @<
UserName = $event.ReplacementStrings[0]
IPAddress = $event.ReplacementStrings[9]
Date = $event.TimeGenerated
DC = $dc.Name
>
$alluserhistory += $userhistory
>
>
>
$alluserhistory
Обратите, что в этом случае вы не увидите события входов пользователей, которые аутентифицировались с клиентов или приложений, которые используют NTLM вместо Kerberos.