Home > Enterprise >  How to set a password for all users (Bash Linux)
How to set a password for all users (Bash Linux)

Time:08-20

how do I set a single password for all users in a Linux system? For example, how will I set a password, x, so that it's the password of all users in the system?

I was thinking of a for loop that iterates between each other but then I realised I have no clue on how to go about this.

CodePudding user response:

You could manually change all user accounts in question with the following, it will prompt you for the new password

$ sudo passwd <username>

You could automate this with a script. Or you could use a convoluted command at the command line, which is what I would do. The below example will pull all users from the passwd file, filter out the users that cannot login, and then run a loop to set their password

  1. using cat piped to grep you can get a list of all users and filter out the users with "nologin" or "false" in their config. If you get users that you do not want, change the filter items or add the username to the grep statement to filter them out, separate each filter item with \|

    $ cat /etc/passwd | grep -Ev nologin\|false

  2. using awk you can get just the username to print out

    $ cat /etc/passwd | grep -Ev nologin\|false | awk '{split($0,a,":");print a[1]}'

  3. running this command in a for loop will let us run a command on each user, to test just echo the username

    $ for user in `cat /etc/passwd | grep -Ev nologin\|false | awk '{split($0,a,":");print a[1]}'`; do echo $user; done

  4. the tricky part is passing a password to the passwd command. switch to the root user and then echo the password to the passwd command. Here is an example

    $ sudo -i
    # (echo 'newpassword'; echo 'newpassword') | passwd <username>

  5. however you do not want the password in your command line history. put the password in a tempfile and then cat it to xargs. As an example, just echo the password using xargs

    $ sudo -i
    # vi tempfile
    enter only one line with the new password
    # cat tempfile | xargs -i echo {}

  6. now you'll use xargs to echo to passwd. this is tricky again because you need to run two echo commands correctly, just tell xargs to run the command in a sub shell

    $ sudo -i
    # cat tempfile | xargs -i /bin/bash -c "(echo '{}'; echo '{}') | sudo passwd <username>"

  7. now add the xargs command in the for loop

    $ sudo -i
    # for user in `cat /etc/passwd | grep -Ev nologin\|false | awk '{split($0,a,":");print a[1]}'`; do cat tempfile | xargs -i /bin/bash -c "(echo '{}'; echo '{}') | sudo passwd $user"; done

That should be it, let me know if you have questions
I tested this example on ubuntu 20.04 using GNU bash 5.0.17

  • Related