Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement