How do I create a user with a password in one line, in Bash, on Redhat?
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.
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".
Alternative:
useradd test echo "username:password" | chpasswd
Tested on: Ubuntu 16.04 / Debian 9
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.