Skip to content

Instantly share code, notes, and snippets.

@wxiaoguang
Last active February 25, 2022 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wxiaoguang/e8436041e43d01f294a7f637ba678482 to your computer and use it in GitHub Desktop.
Save wxiaoguang/e8436041e43d01f294a7f637ba678482 to your computer and use it in GitHub Desktop.
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)
params=$(strField "$passwordSalted" "$" 3)
salted=$(strField "$passwordSalted" "$" 4)
next=$(strField "$passwordSalted" "$" 5)
if [[ "$next" != '' ]]; then
params="$params\$$salted"
salted="$next"
fi
# 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_PARAMS="${params}"
export FV_CHECK_PASSWORD_CLEAR="${passwordClear}"
crypt=$(echo "${passwordClear}" | python3 -c 'import crypt,os; print(crypt.crypt(os.getenv("FV_CHECK_PASSWORD_CLEAR"), "$" + os.getenv("FV_CHECK_PASSWORD_ENC") + "$" + os.getenv("FV_CHECK_PASSWORD_PARAMS") + "$"))')
unset FV_CHECK_PASSWORD_CLEAR
if [[ "$passwordSalted" = "$crypt" ]]; then
echo "OK"
exit 0
else
echo "Error!"
echo "Params=$FV_CHECK_PASSWORD_PARAMS"
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