Linux: Number of days before password expires

While creating a script to send an email alert when a linux accounts password is about to expire, we needed to determine the number of days remaining before expiry. A quick search of Google surprisingly returned only methods that access /etc/shadow, which is not possible for standard users. However, we did manage to come up with a solution.

The following can be used to echo the number of days remaining to stdout:

EXPIRE_DATE=$(chage -l $USER | awk -F ':' '/^Password expires/ { print $NF }')
[[ $(echo $EXPIRES | grep -c 'never') -gt 0 ]] && echo "never" ||  echo "( $(date -d "$EXPIRE_DATE" "+%s") - $(date +%s) ) / 86400" | bc

It’s worth mentioning the “-d” option of the date command that allows a human readable date to be passed in – which is automatically parsed without needing to specify a format specification.

Very useful!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: