Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Encrypt backup files with OpenSSL
#!/bin/bash
#
# 2017-03-11 17:29
# myrveln@gmail.com
#
# Create encrypted tar-archives from folder with OpenSSL.
#
MACHINESDIR="/mnt/input-dir"
ENCRYPTDIR="/mnt/output-dir"
MONTHYEAR=$(date +"%Y-%m")
RETENTION="7"
TAR="/usr/bin/tar"
OPENSSL="/usr/bin/openssl"
PASSWORDFILE="/home/username/.password"
for FOLDER in $(find ${MACHINESDIR}/ -maxdepth 3 -name '*.vmx' -print)
do
MACHINENAME=`echo "${FOLDER}" | cut -d'/' -f6`
BACKUPNAME=`echo "${FOLDER}" | cut -d'/' -f7`
# Check that ${BACKUPNAME}.tar.gz.enc doesn't exist
if [[ ! -f "${ENCRYPTDIR}/${BACKUPNAME}.tar.gz.enc" ]]; then
# Go into parent directory
cd ${MACHINESDIR}/${MACHINENAME}
# Create encrypted tar-archive from ${BACKUPNAME}
${TAR} cz ${BACKUPNAME} | ${OPENSSL} enc -aes-256-cbc -pass file:${PASSWORDFILE} -e > ${ENCRYPTDIR}/${BACKUPNAME}.tar.gz.enc
if [[ $? -eq 0 ]]; then
BACKUP_COUNT="$(ls ${ENCRYPTDIR}/${MACHINENAME}*.tar.gz.enc | wc -l)"
if [[ ${BACKUP_COUNT} -gt "${RETENTION}" ]]; then
DEL=$(expr ${BACKUP_COUNT} - ${RETENTION})
ls -rt ${ENCRYPTDIR}/${MACHINENAME}*.tar.gz.enc | head -n ${DEL} | xargs rm -rf
fi
# Return code is OK. Remove the unencrypted folder.
rm -rf ${MACHINESDIR}/${MACHINENAME}/${BACKUPNAME}
cp ${ENCRYPTDIR}/${BACKUPNAME}.tar.gz.enc ${ENCRYPTDIR}/${MONTHYEAR}-${MACHINENAME}.tar.gz.enc
else
# The encryption went bad.
echo "Encrypt got error \"$?\"!"
fi
else
echo "${BACKUPNAME}.tar.gz.enc already exists. Remove of directory probably failed!"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.