-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
  • 27,991

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
  • 27,991