1

I had written some code that would allow me to make a batch of users based on a file with usernames in it. But it eventually went from just a few lines to about 50, and I deleted it. There has got to be a better way, and I'm stuck.

My goal is to have a bash script that would make multiple users with passwords, and custom UID, and add to groups. Could anyone show me an example of a script that would do this?

2 Answers2

3

Open the terminal and type:

sudo newusers /tmp/userlist.txt  

In the userlist.txt file, each line should contain user data in the following syntax:

username:password:User ID:Group ID:Comments:Userhome directory:User shell  

Since the userlist.txt file contains users' passwords, it should not be stored in a human readable form after you have finished creating the new users. My advice is to store the userlist.txt in a file that is encrypted with a strong password, and then after you have stored the encrypted userlist.txt file securely, to delete the original userlist.txt file from the /tmp directory so that nobody can read the user passwords as plain text.

For more information about the syntax of the newusers command type:

man newusers  

In the man results for newusers the GECOS field is also known as the comment field for a user.

Check /etc/passwd file to see if the new users are created. The easy way to do it is to show a list of only the users' names (There is less unnecessary information to read that way.) using the command:

cut -d: -f1 /etc/passwd  
karel
  • 122,695
  • 134
  • 305
  • 337
  • I saw this and thought wow! Unfortunately, there's a weird long-standing bug on ubuntu where this prog can't do more than 2 users at a time. https://bugs.launchpad.net/ubuntu/+source/shadow/+bug/1266675 – Steph Locke Apr 04 '17 at 15:20
  • wow! indeed and this bug affects an Ubuntu 16.04 user, however when I tested the 2 users example from https://bugs.launchpad.net/ubuntu/+source/shadow/+bug/1266675 on Ubuntu 16.04 the bug was not reproduced. If this bug affects you, then instead of creating a batch of users, as a workaround until the bug is fixed create the users one user at a time. – karel Apr 04 '17 at 15:51
  • Yah, I'm working on that at the mo. For me, annoyingly complex to get working, esp when there's such an elegant method available :) – Steph Locke Apr 04 '17 at 16:33
0

You will need pwgen tool to make random passwords

Make a file (users.txt) with usernames delimited with \n:

userA
userB
userC

Write a bash script that reads from stdin:

while read user
do
  password=$(pwgen -N 1)
  sudo useradd $user -m -s /bin/bash 
  sudo passwd $user $password

  echo Created $user with password $password
done

Lastly, call the script: cat users.txt | /bin/bash my_script.sh

ulicar
  • 21