Учетные данные windows cmd

Диспетчер учетных данных Windows (Credential Manager) позволяет безопасно хранить учетные записи и пароля для доступа к сетевым ресурсам, веб сайтам и приложениям. Благодаря сохраненным в Credential Manager паролям вы можете подключаться без ввода пароля к сетевым ресурсам, которые поддерживаются проверку подлинности Windows (NTLM или Kerbersos), аутентификацию по сертификату, или базовую проверку подлинности.

Содержание:

  • Используем диспетчер учетных данных Windows для хранения паролей
  • Управление сохраненными учетными данными Windows из командной строки
  • Доступ к менеджеру учетных данных Windows из PowerShell

Используем диспетчер учетных данных Windows для хранения паролей

Диспетчер учетных данных встроен в Windows и позволяет безопасно хранить три типа учетных данных:

  • Учетные данные Windows (Windows Credentials) — учетные данные доступа к ресурсам, которые поддерживаются Windows аутентификацию (NTLM или Kerbersos). Это могут быть данные для подключения сетевых дисков или общим SMB папкам, NAS устройствам, сохраненные пароли для RDP подключений, пароли к сайтам, поддерживающих проверку подлинности Windows и т.д;
  • Учетные данные сертификатов (Certificate-Based Credentials) – используются для доступа к ресурсам с помощью сертификатов (из секции Personal в Certificate Manager);
  • Общие учетные данные (Generic Credentials) – хранит учетные данные для доступа к сторонним приложениям, совместимым с Credential Manager и поддерживающим Basic аутентификацию;
  • Учетные данные для интернета (Web Credentials) – сохранённые пароли в браузерах Edge и Internet Explorer, приложениях Microsoft (MS Office, Teams, Outlook, Skype и т.д).

Например, если при доступе к сетевой папке вы включите опцию “Сохранить пароль”, то введенный вами пароли будет сохранен в Credential Manager.

сохранить пароль для доступа к сетевой папке в Windows

Аналогично пароль для подключения к удаленному RDP/RDS серверу сохраняется в клиенте Remote Desktop Connection (mstsc.exe).

Открыть диспетчер учетных данных в Windows можно:

  • из классической панели управления (Control Panel\User Accounts\Credential Manager, Панель управления -> Учетные записи пользователей -> Диспетчер учетных данных);
  • изкоманднойстроки:
    control /name Microsoft.CredentialManager

На скриншоте видно, что в Credential Manager хранятся два пароля, которые мы сохранили ранее.

Менеджер учетных данных в Windows 10, список сохраненных пользователей и паролей

Сохраненный пароль для RDP подключения сохраняется в формате
TERMSRV\hostname
.

Здесь вы можете добавить сохранённый пароль, отредактировать (просмотреть сохраненный пароль в открытом виде из графического интерфейса нельзя) или удалить любую из записей.

Для управления сохраненными паролями можно использовать классический диалоговый интерфейс Stored User Names and Password. Для его запуска выполните команду:

rundll32.exe keymgr.dll,KRShowKeyMgr

Здесь вы также можете управлять сохраненными учетными данными, а также выполнить резервное копирование и восстановление записей в Credential Manager (можно использовать для переноса базы Credential Manager на другой компьютер).

Управление сохраненными учетными данными Windows из командной строки

Вы можете добавить удалить и вывести сохраненные учетные данных в Credentil Manager из командной строки с помощью утилиты cmdkey.

Добавить в диспетчер учетные данные для доступа к серверу FS01:

cmdkey /add:FS01 /user:kbuldogov /pass:Passw0rdd1

Если нужно сохранить доменную учетную запись:

cmdkey /add:fs01.winitpro.local /user:[email protected] /pass:Passw0rdd1

Сохранить учетные данные для доступа к RDP/RDS серверу:

cmdkey /generic:termsrv/MSKRDS1 /user:kbuldogov /pass:Passw0rdd1

Вывести список сохраненных учетных данных:

cmdkey /list

Вывести список хранимых учетных данных для указанного компьютера:
cmdkey /list:fs01.winitpro.local

Удалить ранее сохраненные учетные данные:

cmdkey /delete:FS01

Удалить из Credential Manager все сохраненные пароли для RDP доступа:

For /F "tokens=1,2 delims= " %G in ('cmdkey /list ^| findstr "target=TERMSRV"') do cmdkey /delete %H

Полностью очистить пароли в Credential Manager:

for /F "tokens=1,2 delims= " %G in ('cmdkey /list ^| findstr Target') do cmdkey /delete %H

cmdkey - очистка сохраненных паролей в windows

Также для управления сохраненными учетными данными можно использовать утилиту vaultcmd.Вывести список сохраненных учетных данных типа Windows Credentials:

vaultcmd /listcreds:"Windows Credentials"

утилита vaultcmd для управления сохраненныймаи паролями из командой строки

Все сохраненные пароли хранятся в защищенном хранилище Windows Vault. Путь к хранилищу можно получить с помощью команды:

vaultcmd /list

vaultcmd list: хранилище учетных записей и паролей в windows

По умолчанию это
%userprofile%\AppData\Local\Microsoft\Vault
. Ключ шифрования хранится в файле Policy.vpol. Клю шифровани используется для рашировки паролей в файлах .vcrd.

Для работы Credential Manager должна быть запущена служба VaultSvc:

Get-Service VaultSvc

Если служба отключена, при попытке получить доступ к Credential Manager появится ошибка:

Credential Manager Error
The Credential Manager Service is not running. You can start the service manually using the Services snap-in or restart your computer to start the service.
Error code: 0x800706B5
Error Message: The interface is unknown.

Если вы хотите заблокировать пользователям возможность сохранения сетевых паролей в Credential Manager, нужно включить параметр Network access: Do not allow storage of passwords and credentials for network authentication в разделе GPO Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> Security Options.

отключить возможность сохранения паролей в Credential Manager через групповую политику

Теперь, если пользователь попытается сохранить пароль в хранилище, появится ошибка:

Credential Manager Error
Unable to save credentials. To save credentials in this vault, check your computer configuration.
Error code: 0x80070520
Error Message: A specified logon session does not exist. It may already have been terminated.

Доступ к менеджеру учетных данных Windows из PowerShell

В Windows нет встроенных командлетов для обращения к хранилищу PasswordVault из PowerShell. Но вы можете использовать модуль CredentialManager из галереи PowerShell.

Установите модуль:

Install-Module CredentialManager

powershell модуль CredentialManager

В модуле всего 4 командлета:

  • Get-StoredCredential – получить учетные данные из хранилища Windows Vault;
  • Get-StrongPassword – сгенерировать случайный пароль;
  • New-StoredCredential – добавить учетные данные в хранилище;
  • Remove-StoredCredential – удалить учетные данные.

Чтобы добавить новые учетные данные в хранилище CredentialManager, выполните команду:

New-StoredCredential -Target 'contoso' -Type Generic -UserName '[email protected]' -Password '123qwe' -Persist 'LocalMachine'

New-StoredCredential - добавить пароль в cred manager через powershell

Проверить, есть в хранилище сохраненные данные:

Get-StoredCredential -Target contoso

С помощью командлета Get-StoredCredential вы можете вывести сохраненный пароль, хранящийся в диспетчере учетных данных в отрытом виде.

Выведите список сохраненных учетных данных:

cmdkey.exe /list

Скопируйте значение Target для объекта, пароль которого вы хотите извлечь и вставьте его в следующую команду:

$cred = Get-StoredCredential -Target  LegacyGeneric:target=termsrv/MSKRD2S1
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($cred.Password))

Команда выведет сохраненный пароль в открытом виде.

powershell: получить пароль в открытом виде из диспетчера учетных записей Wndows

Также для получения сохраненных паролей из credman в открытом виде можно использовать утилиты типа Mimikatz (смотри пример).

Сохраненные пароли из Credential Manager можно использовать в ваших скриптах PowerShell. Например, в следующем примере я получаю сохраненные имя и пароль в виде объекта PSCredential и подключаюсь с ними к Exchange Online из PowerShell:

$psCred = Get-StoredCredential -Target "Contoso"
Connect-MSolService -Credential $psCred

Также вы можете использовать Get-StoredCredential для безопасного получения сохранённых учетных данных в заданиях планировщика.

Также обратите внимание на модуль PowerShell Secret Management, который можно использовать для безопасного хранения паролей в Windows (поддерживает различные хранилища паролей: KeePass, LastPass, HashiCorp Vault, Azure Key Vault, Bitwarden.

Чтобы удалить сохраненные учетные данные из Windows Vault, выполните:

Remove-StoredCredential -Target Contoso

Операционные системы семейства Windows содержат много небольших утилит, делающих жизнь администратора проще и удобнее. Но не все из них на слуху, многие незаслуженно обделены вниманием, и, как показал читательский отклик, cmdkey — одна из них. Основная задача этой утилиты — управление учетными данными для доступа по сети и ее возможности трудно переоценить, особенно в одноранговых сетях. Поэтому, если вы или ваши пользователи испытывают затруднения с паролями, теряют доступ к сетевым ресурсам — то вам пора начать применять cmdkey, а как это сделать мы расскажем в данной статье.

Онлайн-курс по устройству компьютерных сетей
На углубленном курсе «Архитектура современных компьютерных сетей» вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

Отношения пользователей и паролей в одноранговых сетях обычно бывают напряженными. Поэтому чаще всего используется гостевая модель доступа, но есть ряд сценариев, когда она неприемлема. Чтобы не быть голословными, приведем пару примеров из жизни.

На компьютере главного бухгалтера установлена 1С, доступ к базе, расположенной на общем ресурсе, должны иметь только бухгалтера, при этом они не должны знать пароля главного бухгалтера. Или у вас есть файловый сервер, доступ к ресурсам которого должен быть разделен между сотрудниками, скажем, чтобы менеджеры отдела продаж не имели доступа к папкам бухгалтерии. Также часто возникает вопрос доступа к различным ресурсам с админскими правами, например, для оснастки управления Hyper-V Server.

Обычно эти вопросы решаются двумя путями: завести на нужном узле все учетные записи пользователей, либо войти с нужного ПК с нужными учетными данными и запомнить пароль. Первый способ подходит в основном для серверов, а второй не отличается стабильностью, система время от времени начинает «забывать» пароли. При этом ситуация может осложняться тем, что пользователь не должен знать используемый пароль (скажем, главбух не хочет, чтобы бухгалтера в ее отсутствие могли войти в систему на ее ПК).

Существует и ряд иных задач, когда нужно входить на удаленный узел с учетными данными отличными от текущих, причем в доменных сетях, с их единым механизмом аутентификации это может быть даже более актуально.

Во всех этих и подобных случаях на выручку придет небольшая утилита командной строки cmdkey. Она позволяет задать учетные данные для доступа к определенному узлу сети. Синтаксис ее прост, для добавления учетных данных используйте:

cmdkey /add:SERVER /user:Ivanov /pass:MyPa$$word

где SERVER — имя сетевого узла, в зависимости от условий вы можете использовать как плоское имя, так и FQDN, следующие две опции задают имя пользователя и пароль, в особых пояснениях не нуждаясь. Для доменных сетей имя пользователя следует указывать вместе с именем домена. Скажем так:

cmdkey /add:srv-01.interface31.lab /user:INTERFACE31.LAB\Ivanov /pass:MyPa$$word

или так:

cmdkey /add:srv-01.interface.lab /user:Ivanov@interface31.lab /pass:MyPa$$word

Ключ add задает учетные данные для сетевого входа в систему, если же вам нужно добавить учетные данные для иных сервисов, скажем терминального сервера, то следует использовать ключ generic:

cmdkey /generic:termsrv/SRV-RDP /user:Ivanov /pass:RdpPa$$word

Все учетные данные, введенные при помощи cmdkey хранятся в системном хранилище и недоступны пользователю. Это безопасно и дает в руки администратора определенную гибкость. Он может на ПК бухгалтеров указать учетные данные для доступа к компьютеру главбуха, но ее пароль останется для них неизвестным.

Посмотреть список сохраненных учетных данных можно командой:

cmdkey /list

cmdkey-001.png

Удалить учетные данные можно следующим образом:

cmdkey /delete:srv-01.interface.lab

Также cmdkey позволяет быстро удалить учетные данные для всех коммутируемых соединений (PPPoE, VPN и т.д.):

cmdkey /delete /ras

Как видим, статья получилась очень даже короткой, в отличие от широких возможностей, которые предоставляет небольшая утилита cmdkey. Надеемся, что данный материал будет полезен широкому кругу администраторов и поможет им в их повседневной деятельности.

Онлайн-курс по устройству компьютерных сетей
На углубленном курсе «Архитектура современных компьютерных сетей» вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

On Windows 11 and Windows 10, Credential Manager is a legacy feature available through Control Panel designed to store sign-in information for websites, apps, and network services (such as shared folders and printers), so you do not have to repeat the credentials in the future.

Although you can store and manage network user information with Credential Manager, it’s also possible to use Command Prompt to add, remove, and view credentials. Usually, this will be helpful when you are building a script, or you are the type that is always working with commands.

In this guide, you will learn the steps to add, remove, and view network user information from Credential Manager using Command Prompt on Windows 10 and Windows 11.

  • Add network credentials with Command Prompt
  • Remove network credentials with Command Prompt
  • View network credentials with Command Prompt

Add network credentials with Command Prompt

To use Command Prompt to add network credentials to Windows 11 or 10, use these steps:

  1. Open Start.

  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.

  3. Type the following command to add a network user and password to Windows and press Enter:

    cmdkey /add:COMPUTER-OR-DOMAIN /user:COMPUTER-OR-DOMAIN\USERNAME /pass:PASSWORD

    In the command, replace COMPUTER-OR-DOMAIN with the target computer, IP address, or domain, COMPUTER-OR-DOMAIN\USERNAME for the target device and username, and PASSWORD for the account password.

    This example creates an entry in Credential Manager for the “admin01” user available in the target computer:

    cmdkey /add:office-pc /user:office-pc\admin01 /pass:password

    cmdkey add command

Once you complete the steps, the user information will store in the Credential Manager.

Remove network credentials with Command Prompt

To remove a network user information from Credential Manager with Command Prompt, use these steps:

  1. Open Start.

  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.

  3. Type the following command to remove a network user from Credential Manager and press Enter:

    cmdkey /delete:COMPUTER-OR-DOMAIN

    In the command, replace COMPUTER-OR-DOMAIN for the name of the target computer, IP address, or domain storing the credentials.

    This example deletes the user credentials for the target device called “office-pc”:

    cmdkey /delete:office-pc
    cmdkey remove command

    cmdkey remove command

View network credentials with Command Prompt

To view all the network users stored in Credential Manager with Command Prompt, use these steps:

  1. Open Start.

  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.

  3. Type the following command to view a list of credentials and press Enter:

    cmdkey /list

    cmdkey list command

  4. (Optional) Type the following command to view a list of credentials from a specific computer and press Enter:

    cmdkey /list:COMPUTER-NAME

    In the command, replace COMPUTER-NAME for the name of the target computer, IP address, or domain storing the credentials.

    This example lists the entries for the target computer called “office-pc”:

    cmdkey /list:office-pc

    cmdkey list computer command

When using this command, you can also see the basic details, such as username, type, target device, etc. You can never view the password by design on Windows 11 or Windows 10.

Why You Can Trust Pureinfotech

The author combines expert insights with user-centric guidance, rigorously researching and testing to ensure you receive trustworthy, easy-to-follow tech guides. Review the publishing process.

When managing user accounts on a Windows PC, it often makes sense to use the Settings app. After all, it provides a graphical user interface that simplifies the process. But for those who’d rather manage the accounts with fewer clicks, they can use the net user command in Command Prompt to manage user accounts on Windows.

In this guide, we’re going to show you how to use the net user command to perform various actions on user accounts on a Windows computer.

1. List All User Accounts

list all user accounts with net user

Before you start managing user accounts with net user, it helps to know all the user accounts on your computer. To list them all, open Command Prompt as an administrator, enter the below command, and hit the Enter key to run it:

        net user
    

Keep the names you see in mind, as you will need them as you use the net user command.

2. Show All the Information of a User Account

user account details while using net user

You can also bring up all the important information about a user by simply typing the net user command followed by the name of the user’s name. Here’s the basic syntax:

        net user Username
    

Let’s say there’s a user named «Jack» on the computer. To bring up their account information, you’d enter the below command, replacing Username in the above command structure with Jack:

        net user Jack
    

Once you run the command, you’ll be able to see, the user’s full name, when their password expires, when they last logged in, whether they’re an administrator, and more.

3. Add and Delete a User Account

To add a new user in Command Prompt, you need to use the net user command followed by the name of the new account, the desired password you wish to set, and the /add switch (this tells net user that you’re adding a user). Here’s the basic syntax of the command:

        net user Username Password /add
    

Keep in mind that all you’ll be creating here is a local account, but you can always switch a local account to a Microsoft account later on. Here’s an example of the command in action:

        net user Jill Pa$$w0rd /add
    

After you run that command, you’ll see that the new user, Jill, has been added to your computer. To delete an account, just replace the /add switch with /delete without specifying the password. Here’s how:

        net user Jill /delete
    

Now net user will remove the account from the computer.

4. Enable and Disable a User Account

deactivating an account with net user

If there’s a user you wish to temporarily restrict so they can’t access their account, you can simply disable it instead of deleting it. Here’s the basic syntax of that action, making sure to use the /active:no switch at the end of the command to tell net user you’re disabling it:

        net user Username /active:no
    

So, here’s an example of what disabling an account would look like after replacing Username with the name of the actual user account:

        net user Jack /active:no
    

And if you want to enable a disabled account, you just have to change the /active:no switch to /active:yes.

5. Enable and Disable a Domain User Account

Sometimes, you might not want a user to access all the resources in a particular domain. The easier way to restrict them is to disable their account in that domain. You can do this by adding the /domain switch to the syntax discussed in the previous section.

Here’s the syntax for disabling an account on a particular domain using net user, making sure to replace Username with the name of the user you want to disable:

        net user Username /domain /active:no
    

If you want to enable an account on a domain, just use the /active:yes switch in the above command structure instead.

6. Set User Account Login Times

If you want to specify the times someone can log in, you can use the /time parameter to specify the account login times. You can use the basic syntax below:

        net user Username /time login_times
    

In the above command structure, replace Username with the user you want to limit the login times for, and login_times with a time range in the format D-D,00:00. Here’s an example of how you’d do this:

        net user Jack /time:M-F,09:00-17:00
    

As per the example above, that user can only log in from Monday to Friday between 9 a.m. and 5 p.m. If Jack tried to log in, he’d get a message saying Your account has time restrictions that prevent you from signing in.

To remove the time restrictions, you’d use the below command:

        net user Jack /time:all
    

Now Jack can go back to logging in whenever he wants.

7. Set User Account Expiry Date

setting an account expiriation date with net user

By default, accounts are set to never expire, but you can change that if you have a user you want to be active for a specific period of time. You will need to use the /expires parameter while specifying the year, month, and expiration date. Here’s the basic command structure:

        net user Username /expires:DD/MM/YYYY
    

An example of this in action would be:

        net user Jack /expires:27/07/2024
    

With the above command, Windows will disable the on the date you’ve set above.

8. Change the Password of a User Account

You can also use the net user command to change the password of a user account in Command Prompt. This will make it so that you can quickly change the password of any local account with a single command, instead of having to do it through the Settings app, which requires many clicks.

The beauty of it is that you can also use it to change passwords for multiple accounts without leaving the Command Prompt window.

9. Change the Password of a Domain User Account

You can also change the password of a user on a domain by appending the /domain switch at the end of the command for changing a user account. The syntax for this is as follows:

        net user Username NewPassword /domain
    

Again this has to be a local domain user account for this to work. So, if you changed the user account from a Microsoft account to a local account, you’ll need to switch it back to use the command.

10. Set a Password Policy for Users

setting an account policy with net user

If you need a particular user to change the password during their next login, you can use the net user command along with the /passwordchg:yes parameter (by default, the parameter is /passwordchg:no). Here’s the basic syntax:

        net user Username /passwordchg:yes
    

Here’s an example of what that would look like in Command Prompt:

        net user Jack /passwordchg:yes
    

So, the next time Jack logs into the computer, he will get a prompt asking him to change his password before he can access his user account.

11. Set a Home Directory for Users

When creating a new user profile using net user, you can set the home directory, which is where Windows will store the user’s personal files and settings. By default, Windows places the home directory of each user account in This PC > Local Disk (C:) > Users. To change this with net user during account creation, the basic syntax is as follows:

        net user Username Password /add /homedir:Path-to-directory
    

A real-world example of this would be:

        net user Jack Pa$$w0rd /add /homedir:D:\Other Users\Jack
    

The above command will place the home directory of Jack, as it creates the account, in the D:\Other Users\Jack folder.

Take Control of Your Computer’s Users Accounts With the Net User Command

Net user is a simple command to understand, allowing you to effectively manage your accounts from one location: Command Prompt. Of course, we haven’t covered everything here, as there are too many parameters and switches to cover in a single guide.

With that said, after you’ve understood how to perform the net user actions we’ve covered, you’ll be on your way to managing accounts on Windows much quicker.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как включить шумоподавление в наушниках windows 10
  • Как полностью отключить защитник windows 11 навсегда
  • Windows media player 12 windows vista
  • Как в windows 10 сделать средство просмотра фотографий программой по умолчанию
  • Чем открыть mdx образ в windows 10