Babin Lonston
Babin Lonston

Reputation: 121

Shell script to send email before password expires

I need to get notify the unix box users when there password going to expires in number of days for that i have used the below script.

#!/bin/sh

[email protected]
[email protected]

for i in babinlonston lonston babin
do

# convert current date to seconds
currentdate=`date +%s`
# find expiration date of user
userexp=`chage -l $i |grep 'Password expires' | cut -d: -f2`
# convert expiration date to seconds
passexp=`date -d “$userexp” +%s`
# find the remaining days for expiry
exp=`expr \( $passexp  – $currentdate \)`
# convert remaining days from sec to days
expday=`expr \( $exp / 86400 \)`
if [ $expday -le 10 ]; then
echo “Please do the necessary action”  | mailx -s “Password for $i will expire in $expday day/s” $rcvr3,$rcvr2
fi
done

When ever i run the script i get the below error.

[root@testvm ~]# sh script.sh
date: extra operand `23,'
Try `date --help' for more information.
expr: syntax error
expr: syntax error
script.sh: line 20: [: -le: unary operator expected
date: extra operand `+%s'
Try `date --help' for more information.
expr: syntax error
expr: syntax error
script.sh: line 20: [: -le: unary operator expected
date: extra operand `+%s'
Try `date --help' for more information.
expr: syntax error
expr: syntax error
script.sh: line 20: [: -le: unary operator expected
[root@testvm ~]#

How can i slove this issue. instead of -le what option i need to use.

Upvotes: 0

Views: 5841

Answers (1)

Andrew Porter
Andrew Porter

Reputation: 156

Don't run it as sh ./script - this will run it in a sh shell. Run it as ./script

I've amended it somewhat and made it more "modern".

#!/bin/bash
#

[email protected]
[email protected]

for i in  babinlonston lonston babin
do

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

  # find expiration date of user
  userexp=$(chage -l $i | awk '/^Password expires/ { print $NF }')

  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 = passexp - currentdate))

      # convert remaining days from sec to days
      (( expday =  exp / 86400 ))

      if ((expday < 10 ))
      then
        echo "Please do the necessary action"  | mailx -s "Password for $i will expire in $expday day/s" $rcvr3,$rcvr2
      fi
    fi
  fi

done

Upvotes: 1

Related Questions