Home > Enterprise >  How to generate password for users and send them email?
How to generate password for users and send them email?

Time:11-15

I have a file with the list of users, I found a way how to generate for each user random password, but didn't know how to select each user their username and password and send them via email (email example [email protected]) the script sends each user an email with each password from the file, that is, if there are 5 users, then each of them will receive 5 emails and 5 different passwords.

Generate Password

#!/bin/bash
file=$(cat /tmp/user_names.txt)

for line in $file
do
    passrand=$(openssl rand -base64 12) 
    echo -e "$line" "$passrand"
done

Send email

#!/bin/bash

for maillogin in $(cut -f1 -d ' ' /tmp/u_p.txt) || pass=$(cut -f2 -d' ' /tmp/u_p.txt)
do
  for pass in $(cut -f2 -d' ' /tmp/u_p.txt)
  do
    echo "Hello your login is" $maillogin "and password is" $pass | mail -s "Test Mail" "${maillogin}@example.com"
  done
done

CodePudding user response:

Your first script is ok.

For the second, you need to read line after line. So, do not use nested loops to read login and password. Use read command and decompose line:

#!/bin/bash

UP_FILE="/tmp/u_p.txt"
while read -r
do
    # maillogin <- line without any characters *after first* space (space included)
    maillogin="${REPLY%% *}"
    # pass <- line without any characters *before first* space (space included)
    pass="${REPLY#* }"
    echo "Hello your login is $maillogin and password is $pass" | mail -s "Test Mail" "${maillogin}@example.com"
done < "${UP_FILE}"
  • Related