Using chpasswd to change account passwords on Linux
The chpasswd command allows admins to change account passwords by piping username and password combinations to it.
This can be done one-account-at-a-time or by putting all of the accounts to be modified in a file and piping the file to the command.
How to use chpasswd
Using the chpasswd command requires root privilege. You can switch to the root account and run a command like this:
# echo nemo:imafish | chpasswd
Better yet, you can use sudo with a command like this:
$ echo skunk:istink! | sudo chpasswd
The usernames and passwords will be in clear text on the command line as shown above, but can also be added to a file like that shown in the two examples below–one running as root, the other using the sudo command:
# cat np $ cat np nemo:imafish nemo:imafish lola:imadog lola:imadog skunk:istink! skunk:istink! # cat np | chpasswd $ cat np | sudo chpasswd
If you use a file like that shown, you should use a command like shred that will thoroughly erase and overwrite the file so that it cannot be recovered from the disk afterwards. Clearly, it’s never a good idea to keep passwords in unencrypted form on your system.
If you’re setting up a password for a new account, it will likely not be usable initially and its /etc/shadow file entry will look something like this:
$ sudo grep skunk /etc/shadow skunk:!!:18935:0:99999:7:::
After using the chpasswd command, the entry will change to something like this with the lengthy password hash included:
$ sudo grep skunk /etc/shadow skunk:$6$qeZmt/yXbkk$PVwHoUY5X/qv9cDK6KNkDCADd87i4h3bHeyfLFNsvQYdmhzZL8rVRTKB9vLT872Dh21K0/KVBUccZ6Vkg34NK/:18935:0:99999:7:::
If you use echo to pipe a username and password to the chpasswd command, the command will likely be recorded in your command history–not a good idea. You could avoid this by disabling the history command’s capture of your commands briefly using this command:
$ set +o history
After running the chpasswd commands that you don’t want recorded, you can reverse that choice like this and return to your normal command history settings:
$ set -o history
If you are changing user passwords, they should be considered temporary, and you should also set the accounts to expire, so users must reset them on their next login. If you are changing passwords for service accounts, ensuring that the passwords cannot be retrieved from the system should be sufficient, as below.
$ sudo passwd -e skunk Expiring password for user skunk. passwd: Success
Tweaking history on Linux can help fine-tune what the history command remembers.
Copyright © 2021 IDG Communications, Inc.