Skip to content

Instantly share code, notes, and snippets.

@KoKuToru
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save KoKuToru/5f8b6ae2de87b003dcc9 to your computer and use it in GitHub Desktop.

Select an option

Save KoKuToru/5f8b6ae2de87b003dcc9 to your computer and use it in GitHub Desktop.
Duplicate remote mysql to local mysql via ssh (gzip'ed)
#!/bin/bash
START=$(date +%s)
HOST="???"
HOST_USER="???"
MYSQL_USER="???"
MYSQL_PASSWORD="???"
MAIL_FROM="???@???"
MAIL_TO="???@???.???"
MAIL_EXTRA="-c [email protected]"
BACKUP_DAYS="30"
uname -a > last_output.txt
date >> last_output.txt
echo >> last_output.txt
#sync remote mysql with local mysql
echo "SYNC MYSQL"
ssh $HOST -l $HOST_USER "mysqldump -u $MYSQL_USER --password=$MYSQL_PASSWORD --all-databases --quick --tz-utc | gzip -c9" | pv | gzip -dc | mysql -u $MYSQL_USER --password=$MYSQL_PASSWORD 2>>last_output.txt
if [ $? -ne 0 ]; then
#error occured
#cat last_output.txt
#echo
echo "SEND SNYC ERROR MAIL"
cat last_output.txt | mail $MAIL_EXTRA -r $MAIL_FROM -s "MySQL Sync Error" $MAIL_TO
else
echo "CREATE BACKUP"
#check if backup folder exists
if [ ! -d "BACKUP" ]; then
mkdir "BACKUP"
fi
echo "CHECK SIZE"
#check size
SIZE=`mysqldump -u $MYSQL_USER --password=$MYSQL_PASSWORD --all-databases | pv | gzip -c9 | wc --bytes`
#check free space
FREE=`df -B1 . | awk 'END{ print $4 }'`
if [ $FREE -le $SIZE ]; then
echo "TOO LESS SPACE"
echo "Zuwenig Speicherplatz" >> last_output.txt
echo >> last_output.txt
df . -H >> last_output.txt
echo >> last_output.txt
ls -lisah BACKUP >> last_output.txt
#cat last_output.txt
#echo
echo "SEND SNYC ERROR MAIL"
cat last_output.txt | mail $MAIL_EXTRA -r $MAIL_FROM -s "MySQL Sync ERROR" $MAIL_TO
else
WANT=`expr $SIZE \* 14`
if [ $FREE -le $WANT ]; then
echo "TOO LESS SPACE SOON"
echo "Speicherplatz wird langsam knapp" >> last_output.txt
echo >> last_output.txt
df . -H >> last_output.txt
echo >> last_output.txt
ls -lisah BACKUP >> last_output.txt
#cat last_output.txt
#echo
echo "SEND SNYC WARNING MAIL"
cat last_output.txt | mail $MAIL_EXTRA -r $MAIL_FROM -s "MySQL Sync Warning" $MAIL_TO
fi
echo "WRITE BACKUP"
#generate backup file
NOW=`date -R`;
mysqldump -u $MYSQL_USER --password=$MYSQL_PASSWORD --all-databases --quick --tz-utc | pv | gzip -c9 > "BACKUP/${NOW}.sql.gz"
echo "REMOVE OLD BACKUPS"
#remove old backups
find BACKUP/* -mtime +$BACKUP_DAYS -exec rm {} \;
fi
fi
END=$(date +%s)
DIFF=$(expr $END - $START)
echo "BACKUP TOOK $DIFF SEC"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment