Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check whether Linux user's password is correct.
#!/bin/bash
checkPassword () {
user="${1}"
passwordClear="${2}"
shadowLine=$(grep "^${user}:" /etc/shadow)
passwordSalted=$(strField "$shadowLine" ":" 2)
enc=$(strField "$passwordSalted" "$" 2)
salt=$(strField "$passwordSalted" "$" 3)
salted=$(strField "$passwordSalted" "$" 4)
# openssl >= 1.1: openssl passwd -${enc} -salt ${salt} -stdin
# mkpasswd (debian: whois, centos: expect):
# python 2 & 3: python -c 'import crypt; print(crypt.crypt("password", "$6$saltsalt$"))'
export FV_CHECK_PASSWORD_ENC="${enc}"
export FV_CHECK_PASSWORD_SALT="${salt}"
export FV_CHECK_PASSWORD_CLEAR="${passwordClear}"
crypt=$(echo "${passwordClear}" | python -c 'import crypt,os; print(crypt.crypt(os.getenv("FV_CHECK_PASSWORD_CLEAR"), "$" + os.getenv("FV_CHECK_PASSWORD_ENC") + "$" + os.getenv("FV_CHECK_PASSWORD_SALT") + "$"))')
unset FV_CHECK_PASSWORD_CLEAR
if [[ "$passwordSalted" = "$crypt" ]]; then
echo "OK"
exit 0
else
echo "Error!"
echo "Shadow=$passwordSalted"
echo "Crypt=$crypt"
exit 1
fi
}
strField () {
str="$1"
sep="$2"
pos="$3"
echo $(echo "$str" | cut -d"$sep" -f "$pos")
}
main() {
user="$1"
[[ "$user" = "" ]] && user=root
echo -n "test password for $user: "
read -s pass
echo "checking password: ${pass:0:4}****** ..."
checkPassword "$user" "$pass"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.