Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Backup MySQL to YandexDisk (OAuth)
#!/bin/bash
#
# # # # # # # # # # НАСТРОЙКИ ДОСТУПА К MYSQL # # # # # # # # # #
MYSQL_SERVER=localhost
MYSQL_USER=root
MYSQL_PASSWORD=password
MYSQL_DATABASES="--all-databases"
# Yandex.Disk настройки (как получить - см. https://oauth.yandex.ru/ и https://oauth.yandex.ru/authorize?response_type=token&client_id=?)
YD_TOKEN=''
YD_STORAGE_PATH='BACKUPS'
# # # # # # # # # # ОБЩИЕ НАСТРОЙКИ # # # # # # # # # #
# Название проекта, используется в логах и именах архивов
PROJECT='project'
# Директория для временного хранения бекапов, которые удаляются после отправки на Яндекс.Диск
BACKUP_DIR='/tmp'
# Имя лог-файла, хранится в директории, указанной в $BACKUP_DIR. Сделать пустым если логи не нужны.
LOGFILE='$PROJECT-backup.log'
# Дата, используется в именах архивов
DATE=`date '+%Y-%m-%d'`
# # # # # # # # # # КОНЕЦ НАСТРОЕК # # # # # # # # # # # # #
function logger()
{
if [[ $LOGFILE != '' ]];
then
echo "["`date "+%Y-%m-%d %H:%M:%S"`"] File $BACKUP_DIR: $1" >> $BACKUP_DIR/$LOGFILE
fi
}
function parseJson()
{
local output
regex="(\"$1\":[\"]?)([^\",\}]+)([\"]?)"
[[ $2 =~ $regex ]] && output=${BASH_REMATCH[2]}
echo $output
}
function checkError()
{
echo $(parseJson 'error' "$1")
}
function getUploadUrl()
{
json_out=`curl -s -H "Authorization: OAuth $YD_TOKEN" "https://cloud-api.yandex.net:443/v1/disk/resources/upload/?path=$YD_STORAGE_PATH/$FILENAME&overwrite=true" `
json_error=$(checkError "$json_out")
if [[ $json_error != '' ]];
then
logger "$PROJECT - GetUploadURL error: $json_error"
else
output=$(parseJson 'href' $json_out)
echo $output
fi
}
function uploadFile
{
local json_out
local uploadUrl
local json_error
uploadUrl=$(getUploadUrl)
if [[ $uploadUrl != '' ]];
then
echo $UploadUrl
json_out=`curl -s -T $1 -H "Authorization: OAuth $YD_TOKEN" $uploadUrl`
json_error=$(checkError "$json_out")
if [[ $json_error != '' ]];
then
logger "$PROJECT - uploadFile error: $json_error"
echo "$json_error"
else
logger "$PROJECT - Copying file to Yandex.Disk success"
fi
else
echo 'Some errors occured. Check log file for detail'
fi
}
logger "--- $PROJECT START BACKUP $DATE ---"
logger "Выгружаем дампы баз"
mkdir $BACKUP_DIR/$DATE
for i in `mysql -h $MYSQL_SERVER -u $MYSQL_USER -p$MYSQL_PASSWORD -e'show databases;' | grep -v information_schema | grep -v performance_schema | grep -v Database`;
do mysqldump -h $MYSQL_SERVER -u $MYSQL_USER -p$MYSQL_PASSWORD $i > $BACKUP_DIR/$DATE/$i.sql;
done
logger "Создаем архив mysql $BACKUP_DIR/$PROJECT-$DATE.tar.gz"
tar -czf $BACKUP_DIR/$PROJECT-$DATE.tar.gz.tar.gz -C $BACKUP_DIR/$DATE .
rm -rf $BACKUP_DIR/$DATE
FILENAME=$PROJECT-$DATE.tar.gz.tar.gz
logger "Выгружаем на Яндекс.Диск архив mysql $BACKUP_DIR/$PROJECT-$DATE.tar.gz.tar.gz"
uploadFile $BACKUP_DIR/$PROJECT-$DATE.tar.gz.tar.gz
logger "Удаляем архивы с диска"
find $BACKUP_DIR -type f -name "*.gz" -exec rm '{}' \;
logger "Завершение скрипта бекапа"
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.