#!/bin/bash # Script Name: dbbackup # Author: Matt McKinnon # Date: 7th June 2016 # Description: # This script will backup your mysql databases. # Send an email report of databases that have been backed up. # Rotate backups for 7 days # # NOTE: # A user will need to be grated permissions on the databases # Login to mysql with your root user. # # CREATE USER 'dbbackup'@'localhost' IDENTIFIED BY 'PASSWORD'; # GRANT LOCK TABLES, SELECT, SHOW VIEW, RELOAD, REPLICATION CLIENT, EVENT, TRIGGER ON *.* TO 'dbbackup'@'localhost'; MAILTO="support@comprofix.com" MAILFROM="support@comprofix.com" SQLSERVER="mysql.comprofix.xyz" SMTP="comprofix-com.mail.protection.outlook.com" BAKDATE=$(date +%Y%m%d) SUBJECT="$SQLSERVER Database Backup Completed - $BAKDATE" DBUSER='dbbackup' DBPASS=$(cat ~/.dbpassword) BACKUPDIR='/mnt/nfs/archive/db/' rotate_backups() { find $BACKUPDIR -type f -mtime +7 -exec rm -frv {} \; } rotate_backups databases=$(mariadb --user=$DBUSER --password=$DBPASS --host=$SQLSERVER -e "SHOW DATABASES;" | tr -d "| " | grep -v Database) for db in $databases; do if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != "sys" ]] && [[ "$db" != "test" ]] && [[ "$db" != _* ]] ; then echo "Dumping database: $db" >> /tmp/dbbackup.msg mariadb-dump --force --opt --user=$DBUSER --password=$DBPASS --host=$SQLSERVER --databases $db > $BACKUPDIR/$db.$BAKDATE.sql fi done #sendemail -o tls=yes -s $SMTP -t $MAILTO -f "$SQLSERVER <$MAILFROM>" -u "$SUBJECT" -m "$(cat /tmp/dbbackup.msg)" -q #Use Below to use systems postfix or local MTA #cat /tmp/dbbackup.msg #| mail -s "$SUBJECT" "$MAIL" #rm -fr /tmp/dbbackup.msg