Write script to create multiple users with pre-defined passwords
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.)
John1024's answer is the correct one - his warning about reading passwords from plain-text files bears repeating.
Let me show the solution in context, without the file-descriptor acrobatics (exec 3<
, ...):
#!/bin/bash# NOTE: Be sure to run this script with `sudo`.# Read user and passwordwhile read iuser ipasswd; 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. # Password is passed via stdin, *twice* (for confirmation). passwd $iuser <<< "$ipasswd"$'\n'"$ipasswd"done < <(paste users.txt passwords.txt)
paste users.txt passwords.txt
reads corresponding lines from the two files and puts them on a single line, separated with\t
.- The result is piped to stdin via a process substitution (
<(...)
). - This allows
read
to read from a single source. $\n
is an ANSI C-quoted string that produces a (literal) newline.
#! /bin/bash for i in {1..100} do `sudo mkdir -p /root/Desktop/userm$i` `sudo useradd -m -d /root/Desktop/userm$i -s /bin/bash userm$i` echo "userm$i:userm$i" | chpasswd done
this will create 100 users.
user name will be (userm1-userm100).
home directory will be /root/Desktop/(userm1-user100)
password will be (userm1-userm100)