Change user password with one Bash command line
Asked Answered
F

4

9

I am making a program with Python 2.7, I use shell commands to create new users on Ubuntu and I want to setup the password for the new user. I use command prompt (Bash) commands to create users. Is there a command line that would change user's password just with 1 shell command? I tried:

echo "newpass" | passwd --stdin user1 

but it appears the current Ubuntu 16.04 version I have doesn't have the --stdin parameter anymore. And I need that after the command is executed, the password would be set, I would not need to retype to confirm password etc (like using terminal).

Fluent answered 13/5, 2017 at 12:45 Comment(2)
This sounds dangerous.Wellspring
@AryaMcCarthy On what basis? :)Bashful
F
22
echo 'user:passwd' | sudo chpasswd

This helped me.

Fluent answered 13/5, 2017 at 13:14 Comment(3)
Well, that is basically what I suggested? And it should be vice versa, i.e.: echo 'user:passwd' | sudo chpasswdSyconium
I'll suggest changing the correct answer to @AndriyBerestovskyy 's one as he replied first and this is just a sample of his answer. In the best case, you could remove your answer and add it as an edit on his answer.Ransom
This is a (poor) copy of the earlier answer by @AndriyBerestovskyy!Emotive
S
21

Please see the man chpasswd(8): man 8 chpasswd

The chpasswd command reads a list of user name and password pairs from
standard input and uses this information to update a group of existing
users. Each line is of the format:

user_name:password

Based on the man you can use: echo 'user:passwd' | sudo chpasswd

Syconium answered 13/5, 2017 at 12:57 Comment(1)
Thanks for digging out the MAN page. I never knew this was possible.Om
M
7

Kindly try below one one-liner command for user & password creation

useradd himanshi ; echo -e "1234\n1234" | passwd himanshi
Monocyclic answered 17/9, 2019 at 4:43 Comment(3)
above trick is also useful when need to create user with password in Ansible. command module will work here.Monocyclic
Can you explain why does this work? Does passwd only read one line at a time and keeps a record where it left off?Azeria
Hi @dtc348. no. but yes you can create in bat in different way as shown below :: Create user net user himanshi 1234 /add :: Set password echo 1234| net user himanshi *Monocyclic
B
3

sudo echo -e "<yourpassword>\n<yourpassword>" | sudo passwd <user>

This helped me.

Burgoo answered 5/4, 2022 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.