Created
June 12, 2018 21:34
-
-
Save efrecon/4114503c79a070716c9e1291607bfb86 to your computer and use it in GitHub Desktop.
Generate and/or update mosquitto password files so content does not gets encrypted twice (and thus rendered unusable) when run. When updating files in place (when no -d option is given) this will simply detect passwords that are already encrypted and **not** touch them.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!/bin/sh | |
warn() { | |
printf "%s\n" "$*" 1>&2 | |
} | |
verbose() { | |
if [ "$VERBOSE" = "1" ]; then printf "%s\n" "$*" 1>&2; fi | |
} | |
# Eat all options so we can pass them to influx when calling it, all remaining | |
# stuff should be file names. | |
DEST= | |
VERBOSE=0 | |
while [ $# -gt 0 ]; do | |
case "$1" in | |
--) | |
# End of options, everything that follows will be filenames | |
shift | |
break | |
;; | |
-d|--destination) | |
DEST="$2" | |
shift 2 | |
;; | |
-v|--verbose) | |
VERBOSE=1 | |
shift | |
;; | |
-*) | |
warn "$1 is an unrecognised option" | |
exit 1 | |
;; | |
*) | |
break; | |
esac | |
done | |
for fname in "$@"; do | |
ORIG=$(mktemp) | |
cp -f ${fname} $ORIG | |
while IFS= read -r line; do | |
line=$(echo "${line}" | sed '/^[[:space:]]*$/d' | sed '/^[[:space:]]*#/d') | |
if [ -n "${line}" ]; then | |
username=$(echo -e "${line}"|cut -d: -f1) | |
passwd=$(echo -e "${line}"|cut -d: -f2) | |
encrypted=$(echo "${passwd}"|grep -E '^\$.*==$') | |
if [ -z "${encrypted}" ]; then | |
if [ -z "$DEST" ]; then | |
verbose "Encrypting password for ${username} in place" | |
# Remove user and re-add it so the password gets encrypted. | |
mosquitto_passwd -D "${fname}" "${username}" | |
mosquitto_passwd -b "${fname}" "${username}" "${passwd}" | |
else | |
# Create empty file if necessary | |
if [ ! -e "${DEST}" ]; then | |
touch "${DEST}" | |
fi | |
already=$(grep -E "^${username}:" "${DEST}") | |
verbose "Encrypting password for ${username} in ${DEST}" | |
if [ -n "${already}" ]; then | |
# Remove user and re-add it so the password gets encrypted. | |
mosquitto_passwd -D "${DEST}" "${username}" | |
mosquitto_passwd -b "${DEST}" "${username}" "${passwd}" | |
else | |
mosquitto_passwd -b "${DEST}" "${username}" "${passwd}" | |
fi | |
fi | |
elif [ -n "$DEST" ]; then | |
already=$(grep -E "^${username}:" "${DEST}") | |
if [ -z "${already}" ]; then | |
verbose "Appending password for ${username} to ${DEST}" | |
echo "${username}:${passwd}" >> ${DEST} | |
fi | |
fi | |
fi | |
done < ${ORIG} | |
rm -f ${ORIG} | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment