1

I'm writing a script and need to check $user if his account has a password set, how can I do this?

I know about this:

passwd --status username

Display account status information. The status information consists of 7 fields. The first field is the user's login name. The second field indicates if the user account has a locked password (L), has no password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days.

but I need something that can fit in a if test

Here is the code:

userPass()
{
    for i in "#@"
    do
        if [ "$i" = root ]
        then
            continue
        else
            echo "Changing password for $i:"
            echo $i:$i"YOURSTRONGPASSWORDHERE" | chpasswd
            if [ "$?" = 0 ]
            then
                echo "Password for user $i changed successfully"
            fi
        fi
    done
}
userPass $1 $2 $3
  • @SivaPrasath updated, it's was there in between all the info – somethingSomething Aug 29 '18 at 6:47
  • @SivaPrasath yes, check if $user/accountt is missing a password – somethingSomething Aug 29 '18 at 6:50
3

How about:

if [ `passwd -S ${i} | cut -d" " -f2` == "P" ]; then do some stuff; fi
5

Since the output of passwd --status indicates whether the user has no password ("has no password (NP)"), you can check that:

if [[ $(passwd --status "$i" | awk '{print $2}') = NP ]]
then
    echo "$i doesn't have a password."
fi

Or:

case $(passwd --status "$i" | awk '{print $2}') in
  NP)  echo "$i doesn't have a password."
       # set password here.
       ;;
  L)  echo "$i's account is locked." ;;
  P)  echo "$i has a password." ;;
esac
  • 1
    +1 for the second option.... – msp9011 Aug 29 '18 at 7:06
  • The first option didn't work as expected and I had to add to it for it to work, don't have here what it was but there are other answers from passwd --status that are not NP but still don't make a password set – somethingSomething Oct 16 '18 at 14:38
  • Whatever you say – muru Oct 16 '18 at 14:48
1

We can also check in /etc/password if we have access.

if [ `awk -F ':' '/^'$i':/ {print $2}' /etc/shadow` ] ; then 
   echo "User has passwd" ; 
else 
   echo "NO passwd";
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.