Linux – Password change Script

cronlinuxpasswordscripting

i am having a file, which contains usernames and encrypted passwords (openssl passwd) in the format user:password.
Now i want to change the password of this User with a Cronjob once a week.
With the help of Janos i made a Script, which changes the password to a $RANDOM generated value, and saves the encrypted password in pw.txt, and the non-encrypted in randompw.txt

r=$RANDOM
cut -d: -f1 pw.txt | while read -r user; do
    echo "$user:$(openssl passwd $r)"
done > newpw.txt
mv newpw.txt pw.txt
echo $r > randompw.txt

So my problems are:
1.) With this, i just have a random generated value for each users, but i want a random value for each user (each line in the file).
2.) It would be good, if i can get the username and the cleartext password of each user into randompw.txt currently, i just have one $RANDOM Password there.

Does anyone has an Idea?

Old post

Best Answer

You can save the generated password in a variable, and write it two files:

  • One file in clear
  • One file hashed

For example:

# initialize (truncate) output files
> clear.txt
> hashed.txt

cut -d: -f1 pw.txt | while read -r user; do        
    # generate a hash from a random number
    hash=$(openssl passwd $RANDOM)

    # use the first 8 letters of the hash as the password
    pass=${hash:0:8}

    # write password in clear formats to one file, and hashed in another
    echo "$user:$pass" >> clear.txt
    echo "$user:$(openssl passwd $pass)" >> hashed.txt
done
Related Question