Skip to content

Instantly share code, notes, and snippets.

@aluferraz
Forked from pugsley/mysql-backup.md
Created March 20, 2018 15:09
Show Gist options
  • Save aluferraz/401fc70a501ffc834cfc554d8e6955d6 to your computer and use it in GitHub Desktop.
Save aluferraz/401fc70a501ffc834cfc554d8e6955d6 to your computer and use it in GitHub Desktop.
MySQL dump > compress > encrypt

Generate openssl keys:

openssl req -x509 -nodes -newkey rsa:2048 -keyout mysqldump-key.priv.pem -out mysqldump-key.pub.pem

Create a mysql default file:

# ~/.mysqldump
[mysqldump]
host = host.here.com
user = user
password = "password"

Bash script:

#!/bin/bash

DATE=`date +%Y-%m-%d-%H-%M-%S`
ARCHIVE=${DATE}.sql.gz.enc
MYSQLINFO=~/.mysqldump
DATABASE=databasename
PUBLIC_KEY=~/.mysqldump-key.pub.pem

mysqldump --defaults-extra-file=${MYSQLINFO} ${DATABASE} --single-transaction --routines --events --triggers \
  | gzip -c \
  | openssl smime -encrypt -binary -text -aes256 -out ${ARCHIVE} -outform DER ${PUBLIC_KEY}

Decrypt & decompress

openssl smime -decrypt -in [filename].sql.gz.enc -binary -inform DEM -inkey mysqldump-secure.priv.pem -out [filename].sql.gz
gzip -d [filename].sql.gz

Clean up backups

cd [dir] && ls -tp | grep -v '/$' | tail -n +8 | xargs -I {} rm -- {}

Keep the latest 7 files in [dir].

References:
https://www.everythingcli.org/secure-mysqldump-script-with-encryption-and-compression/ http://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash

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