'Can't login to ubuntu user even though it is the correct password

Goal: Automate the creation of a user account using a shell script.

Script:

#!/bin/bash
USERNAME="catty"
PASSWORD="$USERNAME@123"

useradd -m $USERNAME -p $PASSWORD

How I run the script in the terminal: sudo sh Scripts/test.sh

What happens: The user account is created successfully

Problem: When I try to login after running the script and I type the correct password which in this case would be "catty@123", it fails to authenticate.

So I checked /etc/shadow using cat. I noticed my password was in hash form as expected however, catty's was not. So then, I manually changed her password and then checked the file again and it was hashed and allowed me to log on successfully.

Why does this happen and what is the solution?



Solution 1:[1]

From man 8 useradd -

-p, --password PASSWORD
   The encrypted password, as returned by crypt(3). 
   The default is to disable the password.

That means useradd expects that the argument given to -p is the hashed form of the password, and adds it to /etc/shadow without changing it.

That's why the password was stored unhashed in your /etc/shadow file. And that's also why you failed to login, because the login program hashes the password you entered before matching it with the entry in /etc/shadow, and the hashed version of kitty@123 doesn't match with kitty@123.

what is the solution?

AFAIK there is no ready-made CLI program that encrypts strings using crypt(3).


P.S. I'm not on a UNIX-like machine right now, so I can't test this, but you could try piping the password to passwd and see if that works.

echo "$PASSWORD" | passwd

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 snath03