3

I want to write a bash script that, when executed, will change all user passwords to one certain password that is specified in the script. Does anyone have any idea how to achieve this? Thanks!

3
  • Do you want to list all users in the script and specify for each one a different password or do you want to specify and set one password for all existing users (which somehow doesn't make sense). Your question is not very clear...
    – Neni
    Jul 17, 2016 at 16:53
  • Hey! I would like to specify one password in the script so when the script runs, it changes every user's password to the one password the is specified in the script. Hope that helps! Thanks
    – wimpycoder
    Jul 17, 2016 at 16:57
  • Sure, but what is the sense of doing this when all users have the same password? Then you better disable passwords for all users...
    – Neni
    Jul 17, 2016 at 16:59

1 Answer 1

3

You can use chpasswd which reads a list of username/password combinations from STDIN and applies them.

To generate the input, we can make a list of all enabled user accounts that have a password set using passwd -Sa | grep -Po "^\S+(?= P)". Then we append a colon ":" and the new password after every username with the help of sed.

This construct would then look like that:

passwd -Sa | grep -Po "^\S+(?= P)" | sed "s/$/:NEWPASSWORD/" | chpasswd

It must be executed as root though, so we must either put it in a script and run that as root (with sudo), or we must run it in a Bash root shell by putting it inside sudo bash -c 'COMMAND'.

Here is the full command you can run, replacing NEWPASSWORD with what you desire.

sudo bash -c 'passwd -Sa | grep -Po "^\S+(?= P)" | sed "s/$/:NEWPASSWORD/" | chpasswd'
2
  • Brilliant answer, may I ask you why there are two '<' after chpasswd? one redirects the stdin for chpasswd, what is the other for? Confused because of the space between them...
    – Neni
    Jul 17, 2016 at 21:09
  • @Neni <( ... ) creates a FIFO (named pipe, like a temporary file) that contains the output of the commands inside. < redirects the contents of a file (the FIFO here) to STDIN of a command. Looking at it again, I could also have used a simple pipe instead: passwd -Sa | grep -Po "^\S+(?= P)" | sed "s/$/:NEWPASSWORD/" | chpasswd. I think I'll edit it and use the pipe, it looks easier.
    – Byte Commander
    Jul 17, 2016 at 22:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .