How to automatically add user and assign random password to the users?

I want to write a script file which will automatically create user and randomly generate passwords. The script that I've written is bellow.

I am still learning so I dont know much. I think I've found what I'm looking for but I am not sure about it. Found solution.

Can anyone please help me with this?

#!/bin/bash
file="/home/dfs/user"
while IFS= read line
do echo "$time"
done < "$file"
useradd Daniel
passwd daniel

1 Answer

with a following script you can generate a random password from a dictionary:

#!/bin/bash
generate_random() { RANDOM_NUMBER=`/usr/bin/perl -e 'print int(rand(60453));'`
}
generate_random
randomWord1=`head -$RANDOM_NUMBER ./dictionary.txt | tail -1`
generate_random
randomWord2=`head -$RANDOM_NUMBER ./dictionary.txt | tail -1`
generate_random
randomWord3=`head -$RANDOM_NUMBER ./dictionary.txt | tail -1`
echo "$randomWord1 $randomWord2 $randomWord3"

in this case create a password concatenating 3 random words from the dictionary.

If you want use it you have to change the following data:

  • name of the dictonary file: dictonary.txt in the example
  • number of words in the dictonary: 60453 in the example

Then you can use it inside a new script to create users and assign them the password generated. This is an example:

#!/bin/bash
PwdGen="./generate_random_password.sh"
# define CSV separator
IFS=";"
while read username FullName
do useradd -m -c "$FullName" $username # Generate random password Pwd=$($PwdGen) # assign the password usermod --password $(echo "$Pwd" | openssl passwd -1 -stdin) $username
done < users_in.csv

This script use the first script (generate_random_password.sh) to generate random password, the create users reading them from input file users_in.csv and assign them the password generated

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like