Создание пользователя из командной строки
Давным-давно прошли те времена, когда при установке Windows приходилось использовать загрузочную дискету. Если бы не эксперименты с переустановкой Windows (помнится восторг от инсталляции Millenium вместо 98) и частое использование CMD и ее утилит, то желание узнать что-то больше, что-то, что лежит за гранью, кануло бы в небытие.
Как правило, в то время основным функционалом (помнится еще и книгу по информатике купил) было использование стандартных утилит, типа dir, copy или format Нынче времена другие, и пожалуй даже школьник средних классов сможет легко обогнать учителя по информатике, если у преподавателя нет интернета, а у школьника есть, плюс, присутствует огромное желание познать что-то новенькое. К великому сожалению, часто приходится видеть этих школьников по телевизору, в новостях с громким название «Школьники украли 5000 долларов с электронных кошельков» или что-то подобное.
Пожалуй, каждый пользователей персонального компьютера с операционной системой Windows хотя бы раз создавал аккаунт, или видел, как это делается. И, пожалуй, многие гордятся, что у них учетная запись с правами Администратора, ну а если они еще и пароль поставят… то, пожалуй, чувствуют себя королем. Если при использовании Панели управления все довольно просто – создал нового юнита, сделал выбора типа «администратор», установил пароль и все, можно спокойно ложиться спать. Однако, если попробовать сделать тоже самое, то есть, создать пользователя из командной строки , то пред нашим взором возникнут много неожиданных и интересных моментов . И так, для того, чтобы добавить или удалить пользователя из командной строки, применяется команда net use, которая используется совместно с такими параметрами:
- /add – добавление нового аккаунта
- /delete – удаление существующего аккаунта
- /comment – позволяет задать описание, например: «для сына» или «только для жены»
- /fullname – тут прописывается полное имя, которое является также отображаемым именем
- /passwordchg : – атрибут yes предоставляет пользователям право изменять в будущем свой пароль (стоит по умолчанию), а no – конечно, запрещает производить столь опасные действия
- /passwordreq: – при условии, если установлен атрибут yes, то требуется наличие пароля
- /active: – значение yes – включение учетной записи (стоит по умолчанию), а no – ее отключение, но не удаление!. Если же во время создания отключить учетную_запись, например:
, то она не будет отображаться во время загрузки системы и даже в аплете «Учетные записи пользователей».
Если запустить команду net user без параметров, то можно увидеть, что кроме пользователя, создание которого производилось из командной строки, есть, и… УчетнаяЗапись Администратор и Гость. К сожалению, данная команда не показывает, какая активирована, а какая нет. Стоит помнить, что встроенные системные Учетные_Записи Администратор и Гость нельзя удалить посредством команды net user Администратор /delete. Их можно только отключить:
Стоит помнить, что данные учетные записи могут иметь и другие названия (Administrator, admin…). А теперь самое интересное, если вы счастливый обладатель XP, ну например SP3 (полагаю, что многое зависит еще и от сборки), то при установке операционной системы, Учетная_Запись «Администратор» остается включенной, более, она не отображается при входе в систему. В интернете есть видео под громким названием «Обходим пароль администратора», так вот, там при входе в систему (при появлении окна приветствия) достаточно было ввести комбинацию CTRL+Alt+DEL (дважды), в появившемся окне ввести Administrator и Enter, вы попадете в систему да еще и с правами администратора! Понятно, что если учетная запись не имеет пароля, и активна, то ничто не мешает попасть в середину. Для любознательных, можно открыть Панель управления/ Администрирование/ Управление компьютером и аналогично посмотреть, какие учетные записи есть и какие активны. Но, если вы счастливый обладатель Семерки, то тут трюк с CTRL+Alt+DEL уже не пройдет, поскольку Администратор отключен.
Но, создав пользователя из командной строки посредством утилиты net user, он автоматически будет зачислен в группу пользователи, что не есть хорошо, особенно, если мы хотим под этим аккаунтом творить свои темные делишки.
И так, следующая команда net localgroup позволяет просматривать имеющиеся в системе группы и добавить нового пользователя из CMD (командной строки) в ту или иную группу. Проделав аналогичные действия, мы увидим, что групп не две как предполагалось (Администраторы и Гости), а значительно больше.
Ладно, добавим NewUser в группу администраторы:
После выполнения данной команды наш новоиспеченный NewUser будет состоять в двух группах – Администраторы и пользователи (при желании можно его и в остальные группы добавить). Удаление пользователя из группы происходит с использованием параметра /delet. Например:
Тут стоит обратить внимание на Семерку, тут есть порой очень раздражающий механизм UAC – контроль учетных записей. При попытке что-то установить или изменить в системе, он предлагает вариант разрешить или нет. Иногда этот механизм не позволяет установить игру или программный пакет (стоит помнить, что некоторые функции CMD работают лишь в том случае, например, создание пользователя из командной строки, если ее запустить от имени администратора), в таком случае можно попробовать активировать встроенную системную запись Администратор и уже под ней произвести нужные действия. НО. После, ее надо или снова отключить, или же поставить пароль, от греха подальше.
Спасибо за внимание. Автор блога Владимир Баталий
Net user command : Manage user accounts from command line
Using Net user command, administrators can manage user accounts from windows command prompt. Below are some examples on how to use this command.
Add a domain user account:
Add new user on local computer:
Advanced options to add new user account can be read in the below article.
Add new user from windows command line.
Disable/Lock a domain user account:
To enable/unlock a domain user account:
Prevent users from changing their account password:
To allow users to change their password:
To retrieve the settings of a user:
thaaaaaaaaanx man for the precious information
One Extra Feature that might be very useful.. is to set the Password to Never Expires:
I am using the /EXPIRES:NEVER switch on the end of the command, however the Never Expires checkbow is not ticked when i check the properties
Please notice that the /expires – switch prevents the the account from expiring, but not to the password.
That’s correct. Thanks Ray for clarifying it here for the benefit of others.
Use This Command To Set “Password Never Expire”
WMIC USERACCOUNT WHERE “Name=’username_here’” SET PasswordExpires=FALSE
Is there a way to change the net user username?
My question is how to create multiple users on a network through a command in command prompt using only single command line.
with a loop for.
FOR/L %variable IN (start, step, end) DO command [Settings]
for /L %U in (10,1,20) do net user user-%U Password /add /dom
(to create 10 users named user-10, user-11 to user-20)
check FOR /F [“options”] %%parameter IN (“Text string to process”) DO command
it’s works but not secure
Very good post on windows command line. Thanks for sharing.
Your command for “Add a domain user account” is incorrect, the proper one is:
Net user domainuser domainpassword /add /domain
Gives result:
“The request will be processed at a domain controller for domain softros.local.
The command completed successfully.”
hi how can i create multiple users from cmd
but just with one command??
i know for creating a new user i can use this:
net user username password /add
and to make him an administrator i can use this:
net user username password administrator /add
correct me if i’m wrong and help me please.
Your query, [hi how can i create multiple users from cmd
but just with one command??] – did you ever get an answer to that question ?
Please let me know.
i am currently locked out of my local administrator account on my windows server 2008 r2
i am able to change user accounts and passwords how ever it still telling me that my username or password is incorrect.
i have created a new user account and password but even the new user account and password doesnt work.
Is there a way to put a number of hours logon to the guest account?
interesting stuff here .. Thanks …
hi every body…
please help me how to add users with environment variable(starting program)?
How can I know who changed password for a user on windows server 2008 R2 from CMD and OS?
How can I check from our Internal domain and not our normal /domain?
Thanks so much! However is there a line to reset a password?
Hi I have forgotten my password to get onto the two accounts set up. When I go into net user neither accounts are showing. I get a message saying
The command completed with one or more errors
Can anyone help
hello guys in my college when i type the command “net users” it shows two accounts one is “guest” and another is “administrator” but in the login screen there are two accounts one is “guest” and another is “ADMIN” .why this ‘ADMIN’ account is not showing in the cmd.
Is there a command line command to add a group or user name under the security tab option Group or user names: for a domain user?
How to check a user which was created in a different trusted domain. Not to the machine joined.
How can we check for an account creation or disablement date in cmd
How can we run a command to replace the email address in AD from powershell
I need your assistance with batch command tomake this change in my secpol.msc!
i need to set the “password policy” > Password must meet complexity….. to be DISABLED or ENABLED
Just be aware that unlocking/enabling a user account also sets it so that the password must be changed on next logon.
I limit login time with “net user time” command of our son account on W10, but when time expire … he is logout from his User account and login under Admin account WITHOUT been asked for Admin´s password!
Any idea why? Thank you.
Please help me can you find the password for profile, when you are on it.
The article seems to think these are the same things.
They are NOT:
Enabled/disable an account.
Lock/unlock an account.
why does the last logon line read “never”? i have this with my current user which i am trying to time restrict. it wont restrict because it claims to have never logged in.
How can I pull the information of a user who is the different domain in Active Directory like IN or BR or AR?
Hello,
Great read! I am hoping u can help me. I am trying to set time limits for a user. However it completed successfully and still allows user to logon when he is not supposed too! Any advice.
what command i can use get net user status in a single query ?i looking for the format
example
account status
admin enabled
Add or Delete Users Account with Command Line in Windows
You can create user accounts separate for each person that will be using your computer. This will allow each Windows user to have their own settings, documents folder, visual style, wallpaper and so on. So separate account for every computer user is much better idea and you can do this simple from command line. To create a new user in windows or to delete a user just follow the steps below. This guide is tested in Windows XP, Vista, Windows 7, 8 and 10.
Add a new user account
Right-click on Command Prompt and select Run as administrator option .
Here how you can find Command Prompt in different Windows versions:
Windows 10 : Rignt-click on Start button and then select “Command Prompt (Admin)” option from menu. Click Yes to UAC alert.
Windows 8 : Hit Windows key from keyboard and type Command Prompt.
Windows 7 / Vista: Hit Windows key and type Command Prompt in start menu box.
XP : Click on Start button > All Programs > Accessories > Command Prompt.
On command line type this command net user UserName Password /add
Where:
UserName = Name of the user account.
Password = Password of the user account.
See the new user account has been added.
Hide password: Instead typing password that is visible while typing, you can type * instead typing complete password like: net user UserName * /add. Here, (*) means when you execute this command by hitting enter, command prompt will ask you to type a password for the user. When you type, password letters will not be displayed on screen.
Make an administrator user account
Default privileges are limited for all user accounts that created from Command Prompt, first you need to create a user account following above commands and then to give administrator privileges to a user you need to run the following command.
net localgroup Administrators UserName /add
Where: UserName is the name of the user account
Error : You might get this error while running commands.
System error 5 has occurred.
Access is denied.
To fix the error your user account must have administrative privileges to run this command. and Command Prompt running with admin rights as well, look at the first paragraph to see how to run command prompt as an admin.
Delete user account
Run Command Prompt as administrator, as we did in Step-1 above.
In command line type this command net user UserName /del
Where:
UserName = Name of the user account that you want to delete
Disable user account command
You might need to disable any Windows user account temporarily, see this guide to enable or disable user account in Windows from command prompt.
Few more “net user” command tips
While adding a new user you can use the following switches with the command to add comments, set full name, password modification rights and more.
/fullname:» » Instead username, specify user’s full name.
/comment:»
» Give descriptive comments (48 character max.) about user account.
/passwordchg:
Usage:
net user UserName Password /add /fullname:”UserFullName”
net user UserName Password /add /comment:”Temporary user for few days.”
net user UserName Password /add /passwordchg:”no”
If you like this guide then, use social buttons and if you want to ask anything please leave a comment below.