- List of user groups command line
- Windows command local user
- Какого назначение системной учетной записи Local System
- Привилегии LocalSystem
- Сценарии вызова командной строки из под System
- Способы вызвать командную строку от имени системы
- Add user to group from command line (CMD)
- Add user to a group
- Few more examples:
- Set-Local User
- Syntax
- Description
- Examples
- Example 1: Change a description of a user account
- Example 2: Change the password on an account
- Parameters
- Inputs
- Outputs
- Notes
List of user groups command line
On Windows OS we can find the list of local user groups created on a system from Contorl Panel -> User Accounts. This information can be obtained from command line also using net command. Syntax is shown below.
Example: Running this command shows the following local groups on my system.
How to list the users in a local group?
Use the below command to know the list of members of a group from command line.
For example to get the list of all remote desktop users on a system we can run the below command.
How to find the list of all groups a user is member of?
You can run the below command to list the groups a user is member of. This command prints the details of the given user account. You can find the group membership information in the last two line of this command output.
Useful references, however “net use username” should be changed to “net user username”
Thank you Kennedy. Corrected the command.
Please get me a command which will display all local users as: LOGIN, FULL NAME, DESCRIPTION, GROUP etc..
I’d just like to express my frustration with this API. As you can see in these examples, thet net API localgroups functionality will happily list all members of a group. However the net user code completely ignores system accounts, as does most of the rest of what Windows makes available. Internally they are organized as a subclass of Win32_Account but not Win32_UserAccount. So it’s possible to retrieve a bunch of useless information from the Windows API. This happens with LookupAccountSid as well. If you give it an SID like S-1-5-20, it will give you an answer. But the answer it gives you can’t be used as input for anything else, which is obnoxious.
You can query if users exist by doing
SET /P query_user=What user do i look for?
::Take out /domain if you want to look on the local computer
Net User %query_user% /domain
if NOT %errorlevel% == 0 goto s_error_1
if %errorlevel% == 0 goto s_success_1
“net user /domain username” lists only the groups to which the username is a direct member. It can’t show nested groups. I was doing a quick check to see if a username was a member of a group:
net user /domain username | find “Group Name”
That fails since the user is not directly a member of “Group Name”. In reality, they are a member, as they’re a member of a nested group.
Any idea of a command line that will expand groups to look for a particular member? I’ve used the “dsquery” and “dsget” commands, but they are only present if the AD tools are installed.
Very useful thanks, didn’t worked for me the first time.
The command is not case sensitive.
For example “NET USER /DOMAIN MYDOMAIN/MyUser” Didn’t worked.
But “NET USER /DOMAIN MyUser” works fine!
So not necessary to put explicitly the domain.
By the way it means also you can’t query another domain than the main one you are logged on to ?
Is there any option where we can get the multiple user’s output in excel for local computer and remote computer
net user userName
Windows command local user
Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов России Pyatilistnik.org. В прошлый раз мы с вами разобрали способы выключения компьютера средствами командной строки, в сегодняшней публикации мы рассмотрим задачу, как вызвать cmd от имени системной учетной записи Local System, рассмотрим варианты применения данной задачи. Думаю, что многим коллегам данная статья будет весьма познавательна и каждый найдет применение данному лайвхаку.
Какого назначение системной учетной записи Local System
Системная учетная запись (Local System) – это специальная встроенная, локальная учетная запись, созданная Windows в момент установки, для использования в системе и запуска из под нее различных служб Windows. В Windows огромное количество служб и процессов для своего запуска и работы используют именно системную запись. Посмотреть это можно в оснастке «Службы», которую можно открыть из окна «Выполнить» введя в нем services.msc.
Учетная запись Ststem не отображается среди других учетных записей в диспетчере пользователей, но зато вы ее легко можете увидеть на вкладке «Безопасность» у любого системного диска, файла. куста реестра или папки. По умолчанию для учетной записи «Система (System)» предоставлены права полного доступа.
Служба, которая запускается в контексте учетной записи LocalSystem, наследует контекст обеспечения безопасности Диспетчера управления службами (SCM). Пользовательский идентификатор безопасности (SID) создается из значения SECURITY_LOCAL_SYSTEM_RID. Учетная запись не связывается с учетной записью любого пользователя, который начал работу. Она имеет несколько значений:
- Ключ реестра HKEY_CURRENT_USER связан с пользователем по умолчанию, а не текущим пользователем. Чтобы обратиться к профилю другого пользователя, имитируйте этого пользователя, а затем обратитесь к HKEY_CURRENT_USER.
- Служба может открыть ключ реестра HKEY_LOCAL_MACHINE\SECURITY.
- Служба представляет мандат компьютера для удаленного сервера. Если служба открывает командное окно (на экране дисплея) и запускает командный файл, пользователь должен нажать CTRL+C, чтобы закончить работу командного файла и получить доступ к окну команды с привилегиями LocalSystem.
Привилегии LocalSystem
- SE_ASSIGNPRIMARYTOKEN_NAME
- SE_AUDIT_NAME
- SE_BACKUP_NAME
- SE_CHANGE_NOTIFY_NAME
- SE_CREATE_PAGEFILE_NAME
- SE_CREATE_PERMANENT_NAME
- SE_CREATE_TOKEN_NAME
- SE_DEBUG_NAME
- SE_INC_BASE_PRIORITY_NAME
- SE_INCREASE_QUOTA_NAME
- SE_LOAD_DRIVER_NAME
- SE_LOCK_MEMORY_NAME
- SE_PROF_SINGLE_PROCESS_NAME
- SE_RESTORE_NAME
- SE_SECURITY_NAME
- SE_SHUTDOWN_NAME
- SE_SYSTEM_ENVIRONMENT_NAME
- SE_SYSTEM_PROFILE_NAME
- SE_SYSTEMTIME_NAME
- SE_TAKE_OWNERSHIP_NAME
- SE_TCB_NAME
- SE_UNDOCK_NAME
Сценарии вызова командной строки из под System
Давайте приведу интересную задачку по нашей теме. Предположим у вас есть доменная среда Active Directory. Вы с помощью инструмента групповой политики или SCCM развернули специализированное ПО, под названием StaffCop, или что-то другое. В момент развертывания или последующей настройки вы задали так, что пользователь даже при наличии прав локального администратора в своей системе не может останавливать службу и менять ее тип запуска, вопрос может ли локальный администратор это поправить и выключить службу?
Способы вызвать командную строку от имени системы
Я очень давно занимаюсь системным администрированием и уяснил давно принцип, если у вас есть права локального администратора, то вы можете все. Обойти любые ограничения и политики. Напоминаю. что я для тестирования развернул агента StaffCop, это такая программа для слежки, которую используют всякие шарашкины конторы. Агент по умолчанию запрещает выключение службы и изменение ее типа. Выглядит, это вот таким образом. Служба работает, имеет имя StaffCop Scheduler, но вот сделать с ней ничего не получается, все не активно.
Для того, чтобы вызвать cmd от имени системы, вам необходимо скачать замечательный набор утилит PSTools, а конкретно нам будет нужна утилита PsExec.exe или PsExec64.exe. Если вы мой постоянный читатель, то вы помните, что я их использовал, чтобы удаленно включить RDP доступ на сервере. Скачать сборник PSTools можно с официального сайта по ссылке ниже, или же у меня с сайта.
Далее вам необходимо распаковать zip архив, в результате чего будет вот такой список утилит.
Теперь когда подготовительный этап готов, то можно продолжать. Откройте обязательно командную строку от имени администратора и введите команду:
Мой пример: cd C:\Дистрибутивы\PSTools
Командой dir я проверил, что это та папка и я вижу нужные мне утилиты PsExec.exe или PsExec64.exe.
Последним шагом мы текущее окно командной строки из под текущего пользователя перезапустим от имени Local System. Пишем:
В итоге я вижу, что у меня открылось новое окно командной строки и оно уже работает в контексте «C:\Windows\system32>«, это и означает учетную запись Local System (Системная учетная запись)
Теперь давайте из под нее попробуем остановить нашу службу StaffCop Scheduler. Для этого есть ряд команд:
Далее вам необходимо изменить тип запуска и поменять с автоматического на отключена. Для этого пишем команду:
Как видим все успешно отработало. Если посмотреть оснастку «Службы», то видим вот такую картину.
Так, что имея права локального администратора и утилиту PsExec.exe, можно делать что угодно. Надеюсь, что вы теперь будите чаще вызывать окно командной строки от имени учетной записи системы. Давайте с вами напишем небольшой батник, который будет из ярлыка вызывать cmd от имени Local System. Создадим тестовый файл, поменяем ему сразу расширение с txt на cmd и откроем его текстовым редактором. Пропишем код:
Щелкаем по файлу правым кликом и выбираем пункт «Запуск от имени администратора». В результате чего у вас сразу будет запущено окно cmd с правами учетной записи SYSTEM. Проверить, это можно введя команду whoami. Ответ NT AUTORITY\СИСТЕМА.
Если нужно запустить удаленно командную строку от имени NT AUTORITY\СИСТЕМА, то выполните такую конструкцию
Add user to group from command line (CMD)
Windows provides command line utilities to manager user groups. In this post, learn how to use the command net localgroup to add user to a group from command prompt’
Add user to a group
Run the steps below –
- Open elevated command prompt
- Run the below command
For example to add a user ‘John’ to administrators group, we can run the below command.
Few more examples:
To add a domain user to local users group:
This command should be run when the computer is connected to the network. Otherwise you will get the below error.
To add a domain user to local administrator group:
To add a user to remote desktop users group:
To add a user to debugger users group:
To add a user to Power users group:
This command works on all editions of Windows OS i.e Windows 2000, Windows XP, Windows Server 2003, Windows Vista and Windows 7. In Vista and Windows 7, even if you run the above command from administrator login you may still get access denied error like below.
The solution for this is to run the command from elevated administrator account. See How to open elevated administrator command prompt
When you run the ‘net localgroup’ command from elevated command prompt:
To list the users belonging to a particular group we can run the below command.
For example to list all the users belonging to administrators group we need to run the below command.
Set-Local User
Modifies a local user account.
Syntax
Description
The Set-LocalUser cmdlet modifies a local user account. This cmdlet can reset the password of a local user account.
The Microsoft.PowerShell.LocalAccounts module is not available in 32-bit PowerShell on a 64-bit system.
Examples
Example 1: Change a description of a user account
This command changes the description of a user account named Admin07.
Example 2: Change the password on an account
The first command prompts you for a password by using the Read-Host cmdlet. The command stores the password as a secure string in the $Password variable.
The second command gets a user account named User02 by using Get-LocalUser. The command stores the account in the $UserAccount variable.
The third command sets the new password on the user account stored in $UserAccount.
Parameters
Specifies when the user account expires. To obtain a DateTime object, use the Get-Date cmdlet.
If you do not want the account to expire, specify the AccountNeverExpires parameter.
Type: | DateTime |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that the account does not expire.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a comment for the user account. The maximum length is 48 characters.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the full name for the user account. The full name differs from the user name of the user account.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the user account that this cmdlet changes. To obtain a user account, use the Get-LocalUser cmdlet.
Type: | Microsoft.PowerShell.Commands.LocalUser |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the name of the user account that this cmdlet changes.
Type: | String |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies a password for the user account. If the user account is connected to a Microsoft account, do not set a password.
You can use Read-Host -GetCredential , Get-Credential, or ConvertTo-SecureString to create a SecureString object for the password.
If you omit the Password and NoPassword parameters, Set-LocalUser prompts you for the user’s password.
Type: | SecureString |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates whether the password expires.
Type: | Boolean |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the security ID (SID) of the user account that this cmdlet changes.
Type: | SecurityIdentifier |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Indicates that the user can change the password on the user account.
Type: | Boolean |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
System.Management.Automation.SecurityAccountsManager.LocalUser, System.String, System.Security.Principal.SecurityIdentifier
You can pipe a local user, a string, or a SID to this cmdlet.
Outputs
None
This cmdlet does not generate any output.
Notes
- The PrincipalSource property is a property on LocalUser, LocalGroup, and LocalPrincipal objects that describes the source of the object. The possible sources are as follows:
- Local
- Active Directory
- Azure Active Directory group
- Microsoft Account
PrincipalSource is supported only by Windows 10, Windows Server 2016, and later versions of the Windows operating system. For earlier versions, the property is blank.