Shell脚本在密码到期之前发送电子邮件

时间:2015-09-21 11:01:05

标签: bash shell sh

我需要通知unix box用户,当密码将在我使用下面脚本的天数到期时。

#!/bin/sh

rcvr1=test1@testvm.localdomain.com
rcvr2=test2@testvm.localdomain.com

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

当我运行脚本时,我收到以下错误。

[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 ~]#

我如何解决这个问题。而不是-le我需要使用什么选项。

1 个答案:

答案 0 :(得分:1)

不要以sh ./script运行它 - 这将在sh shell中运行它。 以./script

运行它

我已经对它进行了一些修改,使它变得更加现代化了#34;

#!/bin/bash
#

rcvr1=test1@testvm.localdomain.com
rcvr2=test2@testvm.localdomain.com

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