useradd has a -p flag, with which you can specify a password ciphertext encrypted with crypt. But later Linuxes don't have crypt.

How can I in a single line, create a new user in RedHat with a pre-defined password?

Update to prevent more drive-by down-voting without context or engagement: My scripting is used inside an automatic setup environment in Amazon Web Services. The script downloads and installs software prerequisites along with the primary line of business application, configures it, adds configuration files for it etc. One of the other things this application needs to do is create an SFTP service to transfer some ledger files backwards and forwards (that service is not under my control, so I can't meet this requirement with public key auth). One of the steps in the automated setup is to create the user that an external system will log on with to do the SFTP-ing, but the useradd command by default in RedHat creates a locked user with no password, then you interactively set a password using passwd. That's not an option in an automated script. The -p flag exists, but it expects ciphertext encrypted with crypt, which itself uses (I think) whatever cryptographic algorithm the shadow file uses, but it seems like that utility hasn't existed in later Linux and Linux-like operating systems for a while. Is the only way around this to encrypt the password on another, older system, and use the ciphertext in the script? It seems like a lot of effort given any passwords in the script are retrieved using KMS decryption so there are no cleartext secrets viewable in the script.

  • 1
    You can make a script like this one: stackoverflow.com/questions/3190955/… – DukeLion Aug 11 '17 at 7:49
  • That question is someone who wants to know if they can use Python to create users, and they are directed to use useradd - which has the problem I originally have. – Elomis Aug 13 '17 at 23:10

This solution should do the trick:

sudo useradd -p $(openssl passwd -1 password) username

This command creates a user with the username "username" and the password "password".


useradd test
echo "username:password" | chpasswd

Tested on: Ubuntu 16.04 / Debian 9

  • Would it be safer to put quotes around $(openssl...) ? – TomOnTime Aug 15 '17 at 0:41
  • Thanks very much, didn't realise openssl could replace the builtin crypt. – Elomis Aug 15 '17 at 23:01
  • 1
    This also works on RedHat – Ian Lim Dec 7 '18 at 7:13

For RedHat (7.3 Maipo for this version), the following not particularly neat solution works:

useradd your-service-user; echo s3cr3tP4ssW0rd! | passwd your-service-user --stdin

This uses the standard input to feed the passwd to add the password.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.