Thursday, June 11, 2020

Linux script to email when user password is going to expire

#!/bin/bash
#

for i in  user1 user2 user3
do

  # convert current date to seconds
  currentdate=$(date +%s)

  # find expiration date of user
  userexp=$(chage -l $i | grep 'Password expires' |cut -d: -f2)

  if [[ ! -z $userexp ]]
  then

    # convert expiration date to seconds
    passexp=$(date -d "$userexp" +%s)

    if [[ $passexp != "never" ]]
    then
      # find the remaining days for expiry
      exp=`expr \( $passexp - $currentdate \)`

      # convert remaining days from sec to days
      expday=`expr \( $exp / 86400 \)`

      if [[ $expday -le 30 ]]
      then
                printf "Automated message from server $HOSTNAME:\n[WARNING] Password for Linux user $i will expire on '$userexp' ($expday day(s) remaining)." | curl --url 'smtp://smtp.server.com' --mail-from 'me@email.com' --mail-rcpt 'support_team@email.com'
      fi
    fi
  fi

done

No comments: