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"
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.
I'm not sure about the password encryption part but I can give a suggestion about the groups. Inside of your loop, you could do this:
read -ra groups_array -d, <<<"$groups"
Now you have an array containing each group as an element. You can pass them as separate arguments to a command using the expansion "${groups_array[@]}"
or access them individually using "${groups_array[0]}"
, "${groups_array[1]}"
, etc.
Note that I am using lowercase variable names - this is intentional. Uppercase names should be reserved for use by the shell, as otherwise you run the risk of overwriting important ones.
Excellent script above: I used the code co create this working version.
#!/bin/bash
function setupUser()
{
echo "remove user: " $1 smbpasswd -d $1 userdel $1
echo "adding user: "$1 useradd $1 -G nogroup echo -e "$2\\n$2\\n" | passwd $1 echo -e "$2\\n$2\\n" | smbpasswd -a $1 }
#---------------------------------------------------------------------------
setupUser tom secret setupUser dick secret setupUser harry secret
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.