bashmultiple-users

BASH script to add username, password and multiple groups


ASSUMPTIONS:

I have a file called users.txt

username:password:groups
user1:password:group1,group2,group3
user2:password:group3
user3:password:group1,group3
user4:password:group2,group3

CODE

#!/bin/bash
FILENAME="users.txt"

while IFS=':' read USERNAME PASSWORD GROUPS
do

    echo "USERNAME" $USERNAME "PASSWORD" $PASSWORD "GROUPS" $GROUPS

done < "$FILENAME"

I want to be able to add a bunch of users to be able to do a samba share. I have a full list of users to input. I am having difficulty mostly with the groups.

Two biggest questions are, how to I get the groups as one string and how do I encrypt the password.

I have been through all tutorials on this site and none of them are working.

Simple to understand code would really help. Thanks.

UPDATED FINISHED WORKING EXAMPLE

#!/bin/bash
# set filename
FILENAME="users.txt"

# loop through file 
while IFS=':' read USERNAME PASSWORD GROUPNAMES
do

    # add user and assign groups
    echo " "
    echo "ADDING USER: " $USERNAME
    useradd $USERNAME -G $GROUPNAMES

    # add password
    echo -e "$PASSWORD\n$PASSWORD\n" | passwd $USERNAME

    # add user to samba
    echo -e "$PASSWORD\n$PASSWORD\n" | smbpasswd -a $USERNAME

done < "$FILENAME"

Solution

  • Don't use GROUPS as a variable name : it's a read-only variable already used by the system. Just change the name of this variable.