Changing a users password inside a script
Posted by Steve on Mon 30 May 2011 at 15:05
In an ideal world you'd never need to change the password associated with a user account without using passwd, but there are times when it is helpful to script such things.
The naive attempts to automate the use of passwd will fail, so the standard advice has always been to use a tool like expect to interactively call the passwd binary.
But there is an alternative approach which is more sensible which is to use the usermod command to change a password.
Assume you have a user account called guest upon your system and you wish to set the user's password to openaccess you can do this by running:
# hash=$(echo openaccess | openssl passwd -1 -stdin) # usermod --pass="$hash" guest
If you wish you could combine that into a single line:
# usermod -p $(echo openaccess | openssl passwd -1 -stdin) guest
If a local user can see the commands you're running in the output of "ps", "top", or similar then this is insecure - but if you generate the hash remotely you should probably be safe enough.