How to programmatically create system user with defined password

It is very easy to add users by hand, but sometimes such actions needs to be automated.

Generate password

The first thing to know is how to generate password using MD5-based algorithm beforehand.

Nothing more then openssl utility is required.

$ openssl passwd -1 "password-string"
$1$CgeyJuTw$DVasTHeH9D01C79lEj9i9.

Check output of the openssl passwd --help command for additional information.

$ openssl passwd --help
Usage: passwd [options] [passwords]
where options are
-crypt             standard Unix password algorithm (default)
-1                 MD5-based password algorithm
-apr1              MD5-based password algorithm, Apache variant
-salt string       use provided salt
-in file           read passwords from file
-stdin             read passwords from stdin
-noverify          never verify when reading password from terminal
-quiet             no warnings
-table             format output as table
-reverse           switch table columns

Create user without disclosing password

You can add new user inside custom shell script using hashed password.

user_password="$1$CgeyJuTw$DVasTHeH9D01C79lEj9i9."
[...]
useradd regularuser11 --create-home --password "$user_password" --shell /bin/bash --uid 5011 --user-group

Create user with disclosed password

Alternatively, you can generate password while adding new user without bothering about its security.

useradd regularuser12 --create-home --password "$(openssl passwd -1 "regularuser12-password")" --shell /bin/bash --uid 5012 --user-group

Additional notes

This is a simple solution, which is ideal for initial system configuration.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system. He is also open for new opportunities and challenges.

Gdansk, Poland https://sleeplessbeastie.eu