- How to get Security Log with non-administrative user
- SHOWTIME
- Manage auditing and security log
- Get-WinEvent VS Get-EventLog
- Non-administrator access to DC Event logs
- Log Off Another User in Windows 10
- To Log Off Another User in Windows 10,
- Log Off Another User from the Command Prompt
- Log Off Another User from with PowerShell
- About Sergey Tkachenko
- 1 thought on “ Log Off Another User in Windows 10 ”
How to get Security Log with non-administrative user
Привет Хабр! Читайте под катом как получить доступ к логу безопасности Windows без прав администратора. Эта будет не первая статья на Хабре связанная с логами Windows и наверно не самая оригинальная, но на мой взгляд я потратил слишком много времени на поиск простого решения для чтения логов обычным пользователем, вот я и решил поделиться «историей своего успеха».
Также пришлось сравнить скорость работы Powershell командлетов Get-WinEvent и Get-EventLog.
Все что находится под катом актуально для Windows Server 2008R2/2012R2, Windows 10 Pro (1809), на других версиях я не проверял, думаю что с продуктами 2016 и 2019 годов ситуация аналогичная.
И так, по умолчанию у рядового пользователя прав на чтение логов безопасности нет.
При попытке получить логи вы получите ошибку.
И через Event Viewer в доступе также будет отказано.
SHOWTIME
Добавим пользователя в локальную группу Event Log Readers.
Далее предоставляем права на чтение ветки реестра MACHINE\System\CurrentControlSet\Services\Eventlog\Security.
Без изменения прав на эту ветку реестра, прочитать параметры лога безопасности не получится, соответственно не получится узнать место расположение и имя файла с логами. Security, это единственный раздел сервиса Eventlog который не наследует права доступа от корня.
Вот как выглядят права для MACHINE\System\CurrentControlSet\Services\Eventlog.
Проверяем, оба командлета Get-WinEvent и Get-EventLog работают!
Позже вернусь к сравнению этих командлетов…
Manage auditing and security log
Если пользователю необходимо предоставить права на отчистку лога, вам придется отредактировать групповую политику. Пользователю или группе пользователей необходимо добавить права Manage auditing and security log.
Находится данная группа тут Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment.
Более подробно про Manage auditing and security log можно прочитать тут
This policy setting determines which users can specify object access audit options for individual resources such as files, Active Directory objects, and registry keys. These objects specify their system access control lists (SACL). A user who is assigned this user right can also view and clear the Security log in Event Viewer. For more info about the Object Access audit policy, see Audit object access.
Проверяем, все работает как и было обещано, логи были отчищены…
Другие логии отчистить прав нету.
Честно говоря, не могу придумать сценарий где пользователю нужно выдать права на отчистку логов безопасности, но такая возможность присутствует.
Get-WinEvent VS Get-EventLog
Пришло время сравнить эти два командлета
The Get-EventLog cmdlet gets events and event logs on the local and remote computers.
You can use the cmdlet’s parameters and property values to search for events. This cmdlet gets events that match the specified property values.
The cmdlets that contain the EventLog noun work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later Windows versions, use Get-WinEvent.
The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the Windows Event Log technology introduced in Windows Vista. It also gets events in log files generated by Event Tracing for Windows (ETW).
Without parameters, a Get-WinEvent command gets all the events from all the event logs on the computer. To interrupt the command, press CTRL + C.
Get-WinEvent also lists event logs and event log providers. You can get events from selected logs or from logs generated by selected event providers. And, you can combine events from multiple sources in a single command. This cmdlet allows you to filter events by using XPath queries, structured XML queries, and simplified hash-table queries
Согласно описания, Get-WinEvent умеет работать с большим количеством журналов которые появились в WIndows Vista.
Для наглядности вот списки с которыми работают эти командлеты, вывод для Get-WinEvent я остановил.
Но есть одно но, производительность имеет значение, сравните время выполнения запросов.
Время работы Get-WinEvent просто поражает, обратите внимание на количество записей в логах Applocation и Security, количество событий примерно одинаковое 3400-3600, но при этом разница по времени выполнения почти 20 раз…
Get-WinEvent тратит 127 секунд против 52 секунд Get-EventLog для чтения событий Application.
И шах и мат, Get-WinEvent тратит 2020 секунд против 45 секунд Get-EventLog для чтения событий Security.
Если выполнить те же команды локально все выглядит не так уж и плохо, но даже локально Get-EventLog работает с логами безопасности в 50 раз быстрее чем Get-WinEvent.
И еще один пример, уже чуть более осмысленный, получения событий с кодом 4624 An account was successfully logged on.
Что тут сказать, цифры не врут…
Non-administrator access to DC Event logs
И на заключение я оставил тему получения доступа к логам безопасности на домен контроллере.
Все выше написанное актуально и для домен контроллера с некоторыми поправками.
1 — Группу Event Log Readers вы найдете в объектах Built-in security principals.
Добавляя пользователя в данную группу вы даете права только на чтение логов на домен контроллерах.
И не забывайте что на каждом из домен контроллеров необходимо дать права на чтение ветки реестра MACHINE\System\CurrentControlSet\Services\Eventlog\Security.
Вот пример, прочитать лог рядового сервера разрешений нет, если вам нужно читать логи с других машин домена, используйте групповые политики, для добавления пользователей или групп пользователей в локальные группы Event Log Readers.
2 – Для добавления прав на отчистку логов необходимо редактировать политику Default Domain Controllers Policy.
3 – Для разрешения запуска заданий от имени пользователя на домен контроллере необходимо также редактировать Default Domain Controllers Policy и дать пользователю права Log on as a batch job.
4 — Будьте предельно внимательными при редактировании дефолтных политик домена!
Краткий список ресурсов, которые мне помогли:
Log Off Another User in Windows 10
How to Log Off Another User in Windows 10
Although the concept of multiple users sharing one device or one PC is getting rarer by the day, there are still cases when you have to share PCs and switch users fast. Sometimes you need to end a session for another user signed in to your computer. Here are a number of methods you can use.
The situation can be different when you need to end a user session. For example, someone just forgot to sign out from his or her user account, and left running apps and opened docs, so the remain in your computer’s memory and consume its system resources. In this case, it could be useful to kick out the inactive session for the other user.
There are no third party tools required. This can be done using either Task Manager, Command Prompt or PowerShell.
To Log Off Another User in Windows 10,
- Open the Task Manager app.
- If it looks as follows, switch it to the full view using the «More details» link in the bottom right corner.
- Click on the Users tab.
- Right-click on a user account you want to log off.
- Select Sign off from the context menu.
Alternatively, there are a couple of console tools we can use for the same purpose. Let’s review them.
Log Off Another User from the Command Prompt
- Open an elevated command prompt.
- Type or copy-paste the following command: query session . This will list available user sessions.
- Note the ID column value for the user you want to sign off.
- Now, execute the command logoff . For example, logoff 1 .
Finally, you can use PowerShell, as follows.
Log Off Another User from with PowerShell
- Open PowerShell as Administrator.Tip: You can add «Open PowerShell As Administrator» context menu.
- Type or copy-paste the following command: $sessionID = ((quser /server:’you computer name’ | Where-Object < $_ -match 'user name to sign off' >) -split ‘ +’)[2]
- Now, execute the command logoff $sessionID .
The PowerShell method is great when you know the exact user name. You can save it as a script and sign out other users with one click when needed.
Related blog posts:
Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:
Share this post
About Sergey Tkachenko
Sergey Tkachenko is a software developer from Russia who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.
1 thought on “ Log Off Another User in Windows 10 ”
To note, the logoff command is not available on Windows 10 Home editions.