Change Password Programmatically

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

Another alternative is to use the yes command in your script.

yes newpassword | passwd youruser

This will send newpassword to the passwd command for youruser.

It should be mentioned that setting/modifying user passwords via scripts may present security risks and should be avoided whenever possible.

EDIT:

This answer requires root access. Apologies for not mentioning this previously. It is a method that I use when performing administration tasks which require root access.

Method 3

The @derobert’s answer is correct but I had to execute the command as superuser like this:

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

Note the sudo after |. sudo at the start won’t help you because it applies only to echo


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x