Baba Mok Baba Mok - 4 months ago 17
Bash Question

Write script to create multiple users with pre-defined passwords

So I would like to make a script that create users from users.txt running

useradd -m -s /bin/false users_in_the_users.txt


and fill the password from passwords.txt twice (to confirm the passwords)

This is the script

#!/bin/bash

# Assign file descriptors to users and passwords files
exec 3< users.txt
exec 4< passwords.txt
exec 5< passwords.txt

# Read user and password
while read iuser <&3 && read ipasswd <&4 ; do
# Just print this for debugging
printf "\tCreating user: %s with password: %s\n" $iuser $ipasswd
# Create the user with adduser (you can add whichever option you like)
useradd -m -s /bin/false $iuser
# Assign the password to the user, passwd must read it from stdin
passwd $iuser
done


The problem is, it does not fill the passwords. And 1 more thing, I want the script to fill the passwords twice.

Any suggestions?

Answer

You have to supply the password on stdin. Replace:

passwd $iuser

with:

passwd "$iuser" <<<"$ipasswd
$ipasswd"

or, as suggested by mklement0:

passwd "$iuser" <<<"$ipasswd"$'\n'"$ipasswd"

The incantation <<< creates a here-string. The string that follows the <<< is provided as standard in to the command which precedes the <<<. In this case we provide the two copies of the password that the passwd command wants.

(The script reads these passwords from a plain text file. I will assume that your situation is some special case for which this is not as dangerous as it normally would be.)