-1

I have one txt in this format:

dfs /home/dfs ashik karki

so now i need a bash script for reading the each word from the text file and what i am going to do is i want to automate adduser and generate random password. Here the user is dfs and home directory is /home/dfs and ashik karki as a comment. So how can i automate this process bu writing a bash script? Thanks!

pLumo
  • 26,947
  • What do you want to do with the comment ? – pLumo Aug 24 '18 at 07:29
  • I felt free to change your title, as reading words from txt file is not the main task here and would have many duplicates on this site ... – pLumo Aug 24 '18 at 08:14

1 Answers1

0

Try this,

# Login as root if necessary
sudo su

# Create your own adduser function to automate the process
adduser2() {
    # add the user
    adduser --home $2 --disabled-login $1
    # Create a password (change 10 to the password length you want)
    local pass=$(openssl rand -base64 10)
    # Change the password
    echo -e "$pass\n$pass" | passwd $1
    # Print information
    echo "Password for user $1: $pass"
    shift 2
    echo "Comment: $@"
}

# Loop through lines in your file and execute the adduser2 function with the line as argument.
while IFS= read -r l; do
    adduser2 $l;
done < file.txt

Notes:

  • This will only work when you have no spaces in /path/to/home
  • You should consider to let the users set a new password on first login --> (see here)
  • If you get a warning unable to write random state, see here.
pLumo
  • 26,947
  • How can i do this without using any loops in a simple way. Is there any other simpler way without making own function? – Ashik Karki Aug 24 '18 at 09:37
  • you want to read information from a file, add users for each line, create a random password, set the password and output the password. That are a number of tasks and as long as there is no specialized app/script to do these, you need to script it on your own. Instead of the function, you could write a script in a file and instead of the loop you can use xargs. But to automate a task like this, I think these few lines of code are not a lot and it's actually quite simply to do ... So I don't see the problem. – pLumo Aug 24 '18 at 10:44
  • #!/bin/bash #apt-get install mkpasswd #pass=$(openssl rand -base64 9) #pass=ashik4331034 read word1 word2 word3 word4 < users.txt /usr/sbin/adduser --home $word2 --gecos "$word3 $word4" $word1 #local pass=$(openssl rand -base64 5) echo -e $pass | usr/bin/passwd $word1 #echo openssl rand -base64 9 | passwd $word1 > passwd.txt #echo $word1:ashik4331034 | chpasswd exit 0 – Ashik Karki Aug 25 '18 at 04:48