Skip to content

Instantly share code, notes, and snippets.

@phlbnks
Created July 26, 2017 08:52
Show Gist options
  • Save phlbnks/f9cca887cc7578b779d8370e81ea1bbd to your computer and use it in GitHub Desktop.
Save phlbnks/f9cca887cc7578b779d8370e81ea1bbd to your computer and use it in GitHub Desktop.
Bash script to help manage .htpasswd files
#!/bin/bash
#
# Manage .htpasswd files
# Store script name for use in output.
me=$( basename $0 )
# Utility function for exiting.
die () {
echo -e "\n${me}: ${1}, exitting...\n" >&2
exit 1
}
# Die immediately if not root.
[ $( id -u ) -gt 0 ] && die "You are not root, do 'sudo $0'"
# Read options.
for i in "$@"
do
case $i in
--files=*)
FILES="${i#*=}" # Space seperated list of .htpasswd file paths under /var/www.
shift # past argument=value
;;
--name=*)
USERNAME="${i#*=}" # Username to set password for.
shift # past argument=value
;;
--password=*)
PLAINTEXT_PASSWORD="${i#*=}" # Plaintext password to be hashed.
shift # past argument=value
;;
*)
# Unknown option.
;;
esac
done
# Prompt for needed vars if missing.
[ -z "$USERNAME" ] && read -p "What username do you want to create/update: " USERNAME
[ -z "$PLAINTEXT_PASSWORD" ] && read -p "Enter the new (plain text) password: " PLAINTEXT_PASSWORD
# Limit things to the webroot.
www_dir='/var/www';
if [[ ! -d $www_dir ]]; then
die "Error: webroot not found"
fi
# If no site(s) passed as arg, find all within webroot.
if [ -z "${FILES}" ]; then
for htpasswd_path in $( cd $www_dir ; find . -type f -iname '.htpasswd' | sort -n ); do
FILES="${FILES} ${htpasswd_path}"
done
fi
# Make sure we're in the webroot.
cd $www_dir
echo -e "\n<== Starting ==>\n"
# Loop over files.
for file in ${FILES}; do
# Pre-flight checks.
[ -z $file ] && \
die "Error: no .htpasswd file(s) found"
[ -r ${file} ] || \
die "Error: '${file}' does not exist"
# Create / modify value for user in *existing* .htpasswd.
echo -e "==> Processing ${file}"
htpasswd -b ${file} "${USERNAME}" "${PLAINTEXT_PASSWORD}"
done;
echo -e "\n<== Done ==>"
exit
@phlbnks
Copy link
Author

phlbnks commented Jul 26, 2017

Add / updates a password for a single user in .htpasswd file(s).
Example usage: $ sudo ./update_htpasswd.sh --name="Bond" --password="Secret Squirrel 007"

  • By default it will run against all .htpasswd files found under the configured webroot, but can also target specific files using the --files= arg.
  • Requires sudo to account for varying permissions. Comment out ln 18 if not needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment