Linux Scripting – Change Password Programmatically

linuxpasswordraspbianscripting

In the current version of Raspian, I know it is possible to change the password of the current logged in user from the command line like so:

sudo passwd

which will then prompt the user to enter a new password twice. This will produce output like so:

Changing password for pi.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

I was wondering if there is a possible way to change a password programmatically, like from a shell script.

I'm trying to make a configuration script to deploy on my Raspberry Pis and I don't want to manually have to type in new passwords for them.

Best Answer

You're looking for the chpasswd command. You'd do something like this:

echo 'pi:newpassword' | chpasswd # change user pi password to newpassword

Note that it needs to be run as root, at least with the default PAM configuration. But presumably run as root isn't a problem for a system deployment script.

Also, you can do multiple users at once by feeding it multiple lines of input.

Related Question