2019年11月29日 星期五

[Linux 常見問題] How to Change Linux User’s Password in One Command Line

Source From Here
Preface
In Linux, we use passwd to change password, but passwd requires input from stdin to get the new password. It is common case that we may want to change the password non-interactively, such as creating new user accounts and change or set password for these accounts on a number of Linux boxes when the new user creating can be done by one command line. 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.

How-To
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 the -e option set. When -e is in effect, escaped characters will be interpreted. Hence, \n in echo’s input is echoed as “new line”. In addition, on modern Linux with sufficiently new passwd, you can use the --stdin option to let passwd accept a password from the STDIN instead of asking for the new password twice.

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)
or
# 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<=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'

If you want to update your own password as a normal user, you may use
$ echo -e "your_current_pass\nlinuxpassword\nlinuxpassword" | passwd

Security notes
You must be aware that the full command line can be viewed by all users in the Linux system and the password in the command line can be potentially leased. Only for cases where this is okay, you may consider using the method here.

Alternative method using chpasswd
chpasswd is a nice tool to change a batch of accounts’ passwords in one Linux box. It can be used to change a user’s password in one command line too. Check its manual for how to use it.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...