Bash – Using hashed password for adduser function in Linux

bashhashsumlinuxshadowuseradd

Sorry, I´m novice in Linux and I am looking for information, how to create new user account in Debian with pre-defined encrypted password.

I have a function in bash, that if new user´s id´s are not presented in my /etc/passwd file than I run the bash command:

adduser -m -p <encrypted-password> <username>

so far so good, but all my data including username and password are stored in JSON output and user´s password is already hashed by SHA-512 (for security reasons). User´s password is encrypted by PHP script and sent to JSON:

$hashed_password = crypt('Test007', '$6$rounds=5000$StJ.1Wji$');
echo looks like this: $6$rounds=5000$StJ.1Wji$cm6ZVl.XoIiQXaJAVHkqiteUGAqZoJ1Ee3dpHP2a6x6rG/kHg4k7ucMLrzHCvQA1TpQYP4eKnoFITVGcviqjU0

After adduser function when I look in my /etc/shadow file, I see that the hashed password is different from original one generated by PHP and of course I cannot login the new user with that password in plain text (even if I know it in plain text).

Is there an easy way, how to create user account with pre-defined encrypted password? How to generated hashed password to be accepted by Linux useradd function? I cannot find any solutions on the internet.

Best Answer

That $6$rounds=5000 is probably part of the problem, because except for the leading $6, the entire value passed to adduser has to be a valid hash. Also (not apparent in your script fragment), the value should be quoted to avoid parameter expansion, e.g.,

adduser -m -p '$6$gehr8sgkkX$lMZ5bmb7c4HY76pnn0uUXA5wH51YE0Byp4rIfcA94gWrVvfeNVQsMwoW2erVuxzFScxRvaHOLFMqVSYCjVlTV/' oneshot

I used mkpasswd to get a value as suggested in How to create an SHA-512 hashed password for shadow?

In a quick check here, the value stored in /etc/shadow matches the value I used when running adduser.