Узнать guid пользователя windows

SID (Security IDentifier) – это уникальный идентификатор, который присваивается пользователям, группам, компьютерам или другим объектам безопасности при их создании в Windows или Active Directory. Windows использует SID, а не имя пользователя для контроля доступа к различным ресурсам: сетевым папкам, ключам реестра, объектам файловой системы (NTFS разрешения), принтерам и т.д. В этой статье мы покажем несколько простых способов получить SID пользователя, группы или компьютера, и обратную процедуру – получить объект по известному SID.

Содержание:

  • Что такое SID объекта в Windows?
  • Как получить SID локального пользователя?
  • Узнать SID пользователя или группы в домене Active Directory
  • Получить SID компьютера
  • Как узнать имя пользователя или группы по известному SID?
  • Поиск объектов в Active Directory по SID

Что такое SID объекта в Windows?

Как мы уже сказали, SID (security identifier) позволяет уникально идентифицировать пользовали, группу или компьютер в пределах определенной области (домена или локального компьютера). SID представляет собой строку вида:

S-1-5-21-2927053466-1818515551-28245911311103.
В данном примере:

  • 2927053466-1818515551-2824591131 – это уникальный идентификатор домена, выдавшего SID (у всего объекта в одном домене эта часть будет одинакова)
  • 1103 – относительный идентификатор безопасности объекта (RID). Начинается с 1000 и увеличивается на 1 для каждого нового объекта. Выдается контроллером домена с FSMO ролью RID Master)

SIDы объектов Active Directory хранятся в базе ntds.dit, а SIDы локальных пользователей и групп в локальной базе диспетчера учетных записей Windows (SAM, Security Account Manager в ветке реестра HKEY_LOCAL_MACHINE\SAM\SAM).

В Windows есть так называемые известные идентификаторы безопасности (Well-known SID). Это SID встроенных (BuiltIn) пользователей и групп, которые есть на любых компьютерах Windows. Например:

  • S-1-5-32-544
    – встроенная группу Administrators
  • S-1-5-32-545
    – локальные пользователи
  • S-1-5-32-555
    – группа Remote Desktop Users, которым разрешен вход по RDP
  • S-1-5-domainID-500
    – учетная запись встроенного администратора Windows
  • И т.д.

В Windows можно использовать различные средства для преобразования SID -> Name и Username -> SID: утилиту whoami, wmic, WMI, классы PowerShell или сторонние утилиты.

Как получить SID локального пользователя?

Чтобы получить SID локальной учетной записи, можно воспользоваться утилитой wmic, которая позволяет обратится к пространству имен WMI (Windows Management Instrumentation) компьютера.

wmic useraccount where name='test_user' get sid

Узнать SID пользователя через WMI

Команда может вернуть ошибку, если репозиторий WMI поврежден. Воспользуйтесь этой инструкцией для восстановления WMI репозитория.

Команда вернула SID указанного пользователя —
S-1-5-21-1175651296-1316126944-203051354-1005
.

Чтобы вывести список SID всех локальных пользователей Windows, выполните:

wmic useraccount get name,sid.

Если нужно узнать SID текущего пользователя (под которым выполняется команда), используйте такую команду:

wmic useraccount where name='%username%' get sid

Можно обратится к WMI напрямую из PowerShell:

(Get-CimInstance -Class win32_userAccount -Filter "name='test_user' and domain='$env:computername'").SID

В новых версиях PowerShell Core 7.x вместо команды Get-WmiObject нужно использовать Get-CimInstance.

Но еще проще получить SID локального пользователя с помощью встроенного PowerShell модуля управления локальными пользователями и группами (Microsoft.PowerShell.LocalAccounts).

Get-LocalUser -Name 'test_user' | Select-Object Name, SID

powershell получить sid локалього пользователя в Windows

По аналогии можно получить SID локальной группы:

Get-LocalGroup -Name tstGroup1 | Select-Object Name, SID

Также вы можете использовать.NET классы System.Security.Principal.SecurityIdentifier и System.Security.Principal.NTAccount для получения SID пользователя с помощью PowerShell:

$objUser = New-Object System.Security.Principal.NTAccount("LOCAL_USER_NAME")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

Узнать SID пользователя или группы в домене Active Directory

Вы можете узнать SID своей доменной учетной записи командой:

whoami /user

whoami user getsid

Получить SID пользователя домена Active Directory можно с помощью WMIC. В этом случае в команде нужно указать имя домена:

wmic useraccount where (name='jjsmith' and domain=′corp.winitpro.ru′) get sid

Для получения SID доменного пользователя можно воспользоваться командлетом Get-ADUser, входящего в состав модуля Active Directory Module для Windows PowerShell. Получим SID для доменного пользователя jjsmith:

Get-ADUser -Identity 'jjsmith' | select SID

get-aduser select sid

Вы можете получить SID группы AD с помощью командлета Get-ADGroup:

Get-ADGroup -Filter {Name -like "msk-admin*"} | Select SID

Get-ADGroup получить sid доменной группы

Если на вашем компьютере не установлен модуль AD для PowerShell, вы можете получить SID пользователя с помощью классов .Net:

$objUser = New-Object System.Security.Principal.NTAccount("corp.wintpro.ru","jjsmith")

$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

PowerShell - get SID via SecurityIdentifier and NTAccount

Эта же команда PowerShell в одну строку:

(new-object security.principal.ntaccount “jjsmith").translate([security.principal.securityidentifier])

Получить SID компьютера

Если компьютер с Windows добавлен в домен Active Directory, у него будет два разных SID. Первый SID – идентификатор локального компьютера (Machine SID), а второе – уникальный идентификатор компьютера в AD.

SID компьютера в домене Active Directory можно получить с помощью команды:

Get-ADComputer srv-rds1 -properties sid|select name,sid

get-adcomputer команда для получения SID компьютера в домене Active Directory

SID локального компьютера (Machine SID) можно получить с помощью бесплатной утилиты PsGetsid (https://docs.microsoft.com/en-us/sysinternals/downloads/psgetsid): Но ее придется скачивать и устанавливать на каждый компьютер вручную.

.\PsGetsid64.exe

Или просто, обрезав последние 4 символа RID и SID любого локального пользователя:

$user=(Get-LocalUser Administrator).sid
$user -replace ".{4}$"

PsGetsid6 вывести machine sid локального компьютера

Важно, чтобы у каждого компьютера в домене был уникальный локальный SID. Если вы клонируете компьютеры или виртуальные машины, или создаете их из одного шаблона, то перед тем как добавить их в домен нужно выполнить команду sysprep. Эта утилита сбрасывает локальный Machine SID. Это избавит вас от частых ошибок “Не удалось восстановить доверительные отношения между рабочей станцией и доменом”.

Как узнать имя пользователя или группы по известному SID?

Чтобы узнать имя учетной записи пользователя по SID (обратная процедура), можно воспользоваться одной из следующих команд:

wmic useraccount where sid='S-1-3-12-12452343106-3544442455-30354867-1434' get name

Для поиска имени доменного пользователя по SID используйте командлеты из модуля
RSAT-AD-PowerShell
:

Get-ADUser -Identity S-1-5-21-247647651-3952524288-2944781117-23711116

Чтобы определить имя группы по известному SID, используйте команду:

Get-ADGroup -Identity S-1-5-21-247647651-3952524288-2944781117-23711116

Get-ADGroup найти группу по SID

Также можно узнать получить SID группы и пользователя с помощью встроенных классов PowerShell (без использования дополнительных модулей):

$objSID = New-Object System.Security.Principal.SecurityIdentifier ("S-1-5-21-2470456651-3958312488-29145117-23345716")
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
$objUser.Value

Поиск объектов в Active Directory по SID

Если вы не знаете к какому типу объекта AD относится SID и какой точно командлет нужно использовать для его поиска (Get-AdUser, Get-ADComputer или Get-ADGroup), вы можете использовать универсальный метод поиска объектов в Active Directory по SID с помощью командлета Get-ADObject

$sid = ‘S-1-5-21-2470146651-3951111111-2989411117-11119501’
Get-ADObject –IncludeDeletedObjects -Filter "objectSid -eq '$sid'" | Select-Object name, objectClass

Get-ADObject поиск объектов в AD по известному SID

В нашем случае объект AD, который имеет данный SID, является компьютером (objectClass=computer).

How to Get Windows User SID

For system administrators, querying information about the environment and configuration is an everyday job. One of these information is the Security Identifier (SID), which is used by Windows to identify users and groups. User names on a network can be duplicated, so that there is no conflict, each user is assigned a unique SID.

When assowing user rights, Windows uses the SID defined for that purpose. A SID is roughly similar to a Globally Unique Identifier (GUID) that each object in Windows owns. However, SIDs receive only security-relevate objects, because the SID is used for authentication of authenticity.

This SID identifies the user across the network. Even if the user’s name is changed, the SID persists, the user on the network is deleted and his SID is unchanged.

Structure of my SID

S-1-5-214147432549-3588766049-1627529166-1001

The SID (Security Identifier) tokens have the following meanings:

S It is a SID
1 Revision
5 Identifier Authority
18 System profiles
19 Localservice
20 Networkservice
21 User profile
4147432549-3588766049-1627529166 Domain ID, Computer ID
1001 User ID (RID)

Table with SID of system accounts

Query SID of all user accounts

If you want to get the SID of all user accounts. You can do so with the following command in a Command Prompt Win+Rcmd

wmic useraccount get sid,name

All SIDs and user names are output.

C:\>wmic useraccount get sid,name
Name SID
Administrator
S-1-5-21-4147432549-3588766049-1627529166-500
DefaultAccount
S-1-5-21-4147432549-3588766049-1627529166-503
John
S-1-5-21-4147432549-3588766049-1627529166-1001
Guest
S-1-5-21-4147432549-3588766049-1627529166-501

Here are the SIDs of the local accounts. For a query in a network domain, there may be some more.

Computer and domain SIDs consist of a base SID and a relative ID (RID) appended to the base SID. If the computer belongs to a domain, another SID comes into play. The computer still has its own computer SID and local accounts and groups. But is also a member of a domain and therefore has a SID that represents the computer account in that domain. The SID of a computer account consists of the SID of the administrator account, minus the RID, which is omitted last 3 bit or 4 bit (500).

Query to get my own user SID

If a user’s SID is to be specifically queried, such as his own user SID, this can be done with the following command.

wmic useraccount where name='%username%' get name,sid

If you want to know another user’s SID, you can specify a user instead of %username%, e.g., john.

The following command detects the SID of the user who is currently logged on in an AD domain.

wmic useraccount where (name='%username%' and domain='%userdomain%') get domain,name,sid

In the opposite way, it is also possible to query the user name of a SID.

wmic useraccount where sid='S-1-5-21-4147432549-3588766049-1627529166-1001' get name

In the PowerShell, the get user SID command looks like this.

[wmi] "win32_userAccount.Domain='$env:UserDomain',Name='$env:UserName'"

The user name and SID of the user logged on to the company domain is output.

PS C:\>[wmi] "win32_userAccount.Domain='$env:UserDomain',Name='$env:UserName'"

AccountType : 512
Caption: company-john
Domain : company
SID : S-1-5-21-4147432549-3588766049-1627529166-1001
FullName : john smith
Name : john

For example, you can use the user SID to find the ProfileImagePath for the user profile in the registry in order to make repairs or adjustments. The user SID is also used as an ObjectID in SQL tables to identify and authorize users from Active Directory in an application, such as Dynamics AX.

Get User SID in Command Prompt or PowerShell. you can use the SID to find the ProfileImagePath for the user profile in the registry

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

on October 24, 2011

In Windows environment, each user is assigned a unique identifier called Security ID or SID, which is used to control access to various resources like Files, Registry keys, network shares etc. We can obtain SID of a user through WMIC USERACCOUNT command. Below you can find syntax and examples for the same.

Get SID of a local user

wmic useraccount where name='username' get sid

For example, to get the SID for a local user with the login name  ‘John’, the command would be as below

wmic useraccount where name='John' get sid

Get SID for current logged in user

To retrieve the SID for current logged in user we can run the below command. This does not require you to specify the user name in the command. This can be used in batch files which may be executed from different user accounts.

wmic useraccount where name='%username%' get sid

Get SID for current logged in domain user

Run the command ‘whoami /user’ from command line to get the SID for the logged in user.
Example:

c:\>whoami /user
USER INFORMATION
----------------
User Name      SID
============== ==============================================
mydomain\wincmd S-1-5-21-7375663-6890924511-1272660413-2944159
c:\>

Get SID for the local administrator of the computer

wmic useraccount where (name='administrator' and domain='%computername%') get name,sid

Get SID for the domain administrator

wmic useraccount where (name='administrator' and domain='%userdomain%') get name,sid

Find username from a SID
Now this is tip is to find the user account when you have a SID. One of the readers of this post had this usecase and he figured out the command himself with the help of the commands given above. Adding the same here.

wmic useraccount where sid='S-1-3-12-1234525106-3567804255-30012867-1437' get name

A Security Identifier or SID is a string value used to identify users or groups and control their access. Here’s how to find the SID of users on your Windows 10, 8, and 7 PC.

1: How to Find Security Identifier (SID) of Users — PowerShell or Command Prompt whoami

Open Powershell or the Command Prompt.

Type in whoami /user and press Enter.

2: How to Find Security Identifier (SID) of Users — PowerShell wmic

Open Powershell.

Type in the following and press Enter:

Current user:
wmic useraccount where name=’%username%’ get domain,name,sid

All users:
wmic useraccount get domain,name,sid

Specific user:
wmic useraccount where name=’username’ get sid

3: How to Find Security Identifier (SID) of Users — PowerShell Get-WmiObject

Open Powershell.

Type in the following and press Enter to get a list of all users:

Get-WmiObject win32_useraccount | Select domain,name,sid

4: How to Find Security Identifier (SID) of Users — Registry Editor

Open the Registry Editor.

Open HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Click on the longer numbers to find the SID, user name and much more.

Similar:

  • How to Check if User Accounts are Administrator or Standard Users
  • How to Check If Users Are Local or Microsoft Accounts in Windows 10
  • Force Users to Change Account Password at Next Login

    comments powered by Disqus

  • Загрузить PDF

    Загрузить PDF

    Из этой статьи вы узнаете, как в Windows выяснить идентификатор безопасности (SID) другого пользователя.

    1. Step 1 Нажмите ⊞ Win+X.

      В левом нижнем углу откроется меню «Опытный пользователь».

    2. Step 2 Нажмите Командная строка (Администратор).

      Откроется новое окно.

    3. Step 3 Щелкните по Да.

      Откроется окно командной строки.

    4. Step 4 Введите WMIC useraccount get name,sid.

      Это команда для отображения идентификаторов безопасности всех пользователей системы.

      • Если вы знаете имя пользователя, введите следующую команду: wmic useraccount where name="USER" get sid (вместо «USER» подставьте имя пользователя).[1]
    5. Step 5 Нажмите ↵ Enter.

      Идентификатор безопасности — это длинная цепочка чисел, которая отобразится справа от каждого имени пользователя.

      Реклама

    Об этой статье

    Эту страницу просматривали 5000 раз.

    Была ли эта статья полезной?

    Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии
  • Удалить сохраненные пароли на сетевые папки windows 10
  • Windows не удалось подключиться к принтеру 0x0000000a windows
  • Поиск в терминале windows
  • Где хранятся скрины на компе на windows 10 win shift s
  • Как почистить полностью компьютер без переустановки windows