Created
October 27, 2020 06:25
-
-
Save justudin/6dfecef1dca738f636bdc495f2d462b4 to your computer and use it in GitHub Desktop.
Backup MongoDB database and send the file to email every month
This file contains hidden or 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 | |
# Make sure to: | |
# - Name this file `backup-monthly.sh` and place it in /home/$userdir | |
# - Run sudo apt-get install sendemail to install the sendemail for sending the backup file through email | |
# - Fill in DB host, name, port number, user and password | |
# - Run chmod +x backup-monthly.sh | |
# - Test it out via ./backup-monthly.sh | |
# - Set up a monthly backup via `crontab -e`: | |
# 0 0 1 * * /home/ubuntu/backup-monthly.sh > /home/ubuntu/backup.log | |
# Mongodb DB host | |
HOST= | |
# Mongodb DB name | |
DBNAME= | |
# Mongodb Port number | |
PORT= | |
# Mongodb user | |
USER= | |
# Mongodb password | |
PASS="" | |
# Current time | |
TIME=`/bin/date +%d-%m-%Y-%T` | |
# Backup directory destination | |
DEST=/home/ubuntu/dbbackups/$TIME | |
# Create backup dir (-p to avoid warning if already exists) | |
/bin/mkdir -p $DEST | |
# ZIP file location | |
ZIP=$DEST/../$TIME.zip | |
# Log | |
echo "Backing up $HOST/$DBNAME to email on $TIME"; | |
# Dump from mongodb host into backup directory | |
/usr/bin/mongodump --host $HOST --port $PORT --username $USER --password $PASS --authenticationDatabase $DBNAME --out $DEST | |
# Create zip with password of backup directory | |
cd $DEST && /usr/bin/zip -P $PASS -r ../$TIME.zip . | |
# SMTP setting for sending through mail | |
SMTP= | |
# SMTP Port | |
SMTP_PORT=587 | |
# SMTP User | |
SMTP_USER= | |
# SMTP Pass | |
SMTP_PASS= | |
TO= | |
SUBJECT="[DBBackup] as of $TIME" | |
BODY="Hello Admin,\nDB Backup operation has been performed for backing up $HOST/$DBNAME at $TIME (d-m-y time).\nPlease find the backup at the attachment.\nKind regards,\nDBBackup Ops" | |
# Send email with backup file is attached | |
/usr/bin/sendemail -f "BackupDBOps <$SMTP_USER>" -t "Admin<$TO>" -o tls=auto -s $SMTP:$SMTP_PORT -xu $SMTP_USER -xp $SMTP_PASS -u $SUBJECT -m $BODY -a $ZIP | |
# Remove zip file locally if you want uncomment this | |
#/bin/rm -f $ZIP | |
# Remove backup directory if you want uncomment this | |
#/bin/rm -rf $DEST | |
# All done | |
echo "Backup and send email operation are done!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment