How can I assign an initial/default password to a user in Linux?

You can use chpasswd to do it, like this:

echo "username:newpassword" | chpasswd

You can pipe into chpasswd from programs other than echo, if convenient, but this will do the trick.

Edit: To generate the password within the shell script and then set it, you can do something like this:

# Change username to the correct user:
USR=username
# This will generate a random, 8-character password:
PASS=`tr -dc A-Za-z0-9_ < /dev/urandom | head -c8`
# This will actually set the password:
echo "$USR:$PASS" | chpasswd

For more information on chpasswd, see http://linux.die.net/man/8/chpasswd

(Command to generate password was from http://nixcraft.com/shell-scripting/13454-command-generate-random-password-string.html)


You can use OpenSSL to generate the random password (16 characters, in this case):

# 1000 bytes should be enough to give us 16 alphanumeric ones
p=$(openssl rand 1000 | strings | grep -io [[:alnum:]] | head -n 16 | tr -d '\n')

Then feed the hashed password to useradd or usermod

# omit the "-1" if you want traditional crypt()
usermod -p $(openssl passwd -1 "$p") <username>

EDIT:

Since posting this in 2012, newer versions of OpenSSL have added functionality to the openssl passwd command. Instead of using the -1 option to get an MD5-based hash, modern versions also support -5 for SHA256-based hashes and -6 for SHA512-based hashes.


Credit where due: The password generation is adapted from a similar method that uses /dev/urandom instead of openssl.


useradd should work (I've done it on Ubuntu). Maybe check that each of your args are correct (thee groups exist, the path is right to bash). You can run the command with just a password and user, and then use userdel to remove and then retry with more parameters, to see what one causes the issue (brute force approach).

There is also newusers (see the man page), at least under Ubuntu, where you give it a file with passwd file like info, including plain text passwords and it will create those users. Nice way to do many users at once.