#!/bin/bash ################################################################################ # Global variables ################################################################################ USER_TO_CHANGE="" NEW_PASSWORD="" MY_NAME=$(basename "$0") ################################################################################ # Functions ################################################################################ die() { printf '%s\n' "$1" >&2 exit 1 } show_help() { cat << HELP Script to update the password of a user. The password is either - entered interactively - redirected from STDIN via ${MY_NAME} ... <<< 'newpassword' - redirected from a file via ${MY_NAME} ... < /path/to/file-with-password Usage: $1 [OPTION] Mandatory: -u|--user USER the username for password change HELP } check_if_root() { if [ ${EUID} -ne 0 ]; then echo "Script must be run as root or sudo" return 1 fi return } check_user() { if [ "${USER_TO_CHANGE}" == "" ]; then echo "User cannot be empty." exit 1 fi if ! id "${USER_TO_CHANGE}" &> /dev/null ; then echo "User \"${USER_TO_CHANGE}\" does not exist." exit 1 fi return } get_password() { if test -t 0; then echo -n "New password: " fi IFS= read -rs NEW_PASSWORD PW_CHANGE_SUCCESS=$? echo "" if [ $PW_CHANGE_SUCCESS -ne 0 ]; then echo "Couldn't read new password." exit 1 fi if [ "${NEW_PASSWORD}" == "" ]; then echo "New passord cannot be empty." exit 1 fi return } change_user_password() { CHPASSWD_OUT=$(chpasswd <<< "${USER_TO_CHANGE}:${NEW_PASSWORD}" 2>&1) if [ $? -ne 0 ]; then echo "Password change failed. Error is:" echo "${CHPASSWD_OUT}" exit 1 fi return } ################################################################################ # Argument parser ################################################################################ while :; do case $1 in -h|-\?|--help) show_help # Display a usage synopsis. exit ;; -u|--user) # Takes an option argument; ensure it has been specified. if [ "$2" ]; then USER_TO_CHANGE=$2 shift else die 'ERROR: "-u|--user" requires a non-empty option argument.' fi ;; -p|--password) # Takes an option argument; ensure it has been specified. if [ "$2" ]; then NEW_PASSWORD=$2 shift else die 'ERROR: "-u|--user" requires a non-empty option argument.' fi ;; --) # End of all options. shift break ;; *) # Default case: No more options, so break out of the loop. break esac shift done ################################################################################ # Main, main, main ################################################################################ check_if_root check_user get_password change_user_password