I frequently create new user accounts and change or set password for these accounts on a batch of Linux boxes. The create new user can be done by one command line. The problem is to change the password. In Linux, we use passwd to change password, but passwd requires input from stdin to get the new password. With the help of pipe and a little tricky, we can change user’s password in one command line. This will save much time especially when creating a batch of user accounts.
We use one example to introduce how to change Linux user’s password in one command line. Suppose we login as root and want to change user linuxuser‘s password to linuxpassword.
The passwd command asks for the new password twice. And these two inputs (the same password) is separated by one “Enter”. We can emulate this by the echo command with ‘-e’ option set. When ‘-e‘ is in effect, ‘n‘ in echo’s input is echoed as “new line”.
So to change the password in our example, we just execute this one command:
# echo "linuxpassword" | passwd --stdin linuxuser
on modern Linux. (Thanks to DAVID for this tip)
# echo -e "linuxpassword\nlinuxpassword" | passwd linuxuser
This can also be put into one bash script or executed on remote node by the
ssh command. For example, we can change the password of linuxuser on a batch of servers (100 servers: 10.1.0.1 to 10.1.0.100) by:
# for ((i=1;i&lt;=100;i++)); do ssh 10.1.0.$i 'echo -e "linuxpassword\nlinuxpassword" | passwd linuxuser'; done;
Even further, we can create one user and set its initial password remotely by:
# ssh remoteserver 'useradd newuser; echo -e "passwdofuser\npasswdofuser" | passwd newuser'