Problem statement:
Change or set a Linux user's password non-interactively. Consider a scenario that you have to create multiple user accounts with a default password on a server.
I can use
So, it is certainly not handy when you have to create hundreds of user accounts and set their passwords, as one has to enter the same password twice per user multiplied by the number of user accounts to be created.
Solution:
We know that,
This way, we can send the password twice in one shot using
A better approach to set a user accounts password is to use
With this, we can change the password of user account
Alternately, you can mention usernames and passwords in a file in
You can use any of this tricks in your script to automate changing or updating Linux user account's password. Try and let us know how it goes for you.
Change or set a Linux user's password non-interactively. Consider a scenario that you have to create multiple user accounts with a default password on a server.
I can use
passwd
command, but it expects user input through stdin
.$ passwd foouser Enter new UNIX password: [NEW PASSWORD] Retype new UNIX password: [NEW PASSWORD]
So, it is certainly not handy when you have to create hundreds of user accounts and set their passwords, as one has to enter the same password twice per user multiplied by the number of user accounts to be created.
Solution:
We know that,
passwd
commands expects the new password to be provided through stdin
twice, with a ENTER key i.e. new line separating those inputs. We can reproduce this using echo
as:$ echo -e "newpasswd\nnewpassword" newpasswd newpasswd
This way, we can send the password twice in one shot using
echo
command and a new line character \n
as:$ echo -e "newpasswd\nnewpassword" | passwd foouser
A better approach to set a user accounts password is to use
chpasswd
command. This command is used especially when you have to create multiple user accounts and set/update their passwords in a batch. It reads user-password pair from stdin
in userName:newPassword
format and changes the password of user account userName
to newPassword
.With this, we can change the password of user account
foouser
to newpassword
as:$ echo "foouser:newpasswd" | chpasswd
Alternately, you can mention usernames and passwords in a file in
userName:newPassword
format, one pair per line, and feed that to chpasswd
command.$ cat secretfile user1:newpassword1 user2:newpassword2 user3:newpassword3 ... ... $ cat secretfile | chapasswd
You can use any of this tricks in your script to automate changing or updating Linux user account's password. Try and let us know how it goes for you.
Good Tutorial. Thanks.
ReplyDelete