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"

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.

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.