Import users from CSV file

Solution 1:

There's an app for that! The newusers tool which is part of the passwd package is designed to batch create users:

DESCRIPTION
   The newusers command reads a file (or the standard input by default)
   and uses this information to update a set of existing users or to
   create new users. Each line is in the same format as the standard
   password file (see passwd(5)) with the exceptions explained below:

You will need to create a file with this format:

username:passwd:UID:GID:full name,room number,work phone,home phone,other:directory:shell

Many of these can be ignored and the default values will be used. You only need to specify the username and password. For example:

tom:password1:::::
danny:password2:::::

If I save that as users.txt and run this command:

sudo newusers < users.txt 

The users are created:

$ grep -E 'tom|danny' /etc/passwd
tom:x:1005:1006:::
danny:x:1006:1007:::

Solution 2:

With a script you can. This needs a file with user and password commaseparated:

while IFS="," read -r user passwd ; do      
        echo "useradd -m -p $(mkpasswd "$passwd") $user"
done < /home/$USER/Downloads/users.txt
  • mkpasswd can be installed with sudo apt-get install whois
  • Change the , to a ; if you need that.

Save this as users.sh and set permissions with chmod +x users.sh

If you then do

./users.sh > users_create.sh

You get a text file with all the commands so you can verify it and

chmod +x users.sh
./users_create.sh

will then create them.


Testing

Example file:

wdn,password123 
wdn2,password345

saved as "users.txt" in "~/Downloads".

Execute script:

./users.sh 
useradd -m -p acBNi2tbw9iaw wdn
useradd -m -p OHOzeMGqbcMso wdn2

and

./users.sh  > users_create.sh
~/Downloads$ more users_create.sh 
useradd -m -p Q1BVotdoA3ucI wdn
useradd -m -p siUX7mYTYw.3A wdn2

(password are encrypted).

After this all you need to do is execute is to make this executable with chmod +x users.sh and execute it with ./users_create.sh (I did not do that last bit so if not working please comment).