[TOC]

0x00 前言说明

描述:本文章是为了记录在日常MySQL运维中对数据库进行操作处理的Shell脚本编写,做一个备份说明;

0x01 备份

1.Mysql数据库备份自动删除

#!/bin/bash
#Func:数据库备份并删除10天的备份文件
read -t 30 -p "请输入数据库备份得路径:" dir
filename="${dir}db_time.$(date "+%Y-%m-%d").sql"
mysqldump --database db_time -u root -p root > $filename
#获取日期当前减去10天(也可以使用ls列举出前十天的文件进行全部删除)
d=$(date -d "-10 day" +%Y-%m-%d)
#删除10天前的备份文件
del_file="${dir}db_time.${d}.sql"
rm -rf $del_file


2.mysql多数据库与表备份
描述:分表备份与备份数据库差不多,优缺点:文件多,分布;碎

#linux
mysql -uroot -p123456 -e "show databases;" | grep -Evi "database|info|perfor" | sed -r 's#^([a-z].*$)'#mysqldump -uroot -p123456 --event -B \1|gzip > /opt/backup/\1.sql.gz#g' | bash //bash是执行

#windwows (git)
mysql -uroot -p123456 -e "show databases;" | findstr /V /I "Database information performance" |sed -r "s#^([a-z].*$)# mysqldump.exe -uroot -p123456 --events -B \1|gzip >.\/backup\/\1.sql#g"|cmd

#分表备份:
mysql -uroot -p123456 -e "use demo;show tables" | findstr "u w"

相关脚本:

#shell脚本
#!/bash/bin
for down in `mysql -uroot -p123456 -e "show databases;" | grep -Evi "database|information|performance"`
do
mysqldump -uroot -p123456 --events -B $down|gzip > /opt/back/${down}_bak.sql.gz
done

#bat脚本
@echo off
mysql -uroot -p123456 -e "show databases;" |findstr /V /I "Database information performance" > data.txt
for /f "" %%v IN (data.txt) DO @mysqldump.exe -uroot -p123456 --events -B %%v|gzip >> ./backup/%%v.sql.gz
echo "备份完成"
del /s /f /q data.txt

WeiyiGeek.


0x02 主从相关

1.主从库一键自动化主从复制脚本

#(1)模式主从同步的步骤,获取到全备及全备过程的binlog位置信息或者直接使用--master-data参数解决;
#---- master 主库 ----#
#!/bin/bash
MYUSER="root"
MYPASS="123456"
MYSOCK=/data/3306/mysql.sock
MAIN_PATH=/server/backup
LOG_FILE=${MAIN_PATH}/logs_`date +%F`.log
DATA_FILE=${MAIN_PATH}/backup_`date +%F`.sql.gz
MYSQL_PATH=/usr/local/mysql/bin
MYSQL_CMD="${MYSQL_PATH}/mysql -u$MYUSER -p$MYPASS -S $MYSOCK"
MYSQL_DUMP="${MYSQL_PATH}/mysqldump -u$MYUSER -p$MYPASS -S $MYSOCK -A -B --master-data=1 --single-transaction -e" #single-transaction 针对于Innodb备份 (全备)
#值得学习的地方 (注意采用EOF可以输入多行命令)
cat | $MYSQL_CMD<< EOF
flush tables with read lock;
system echo "--show master status --" >>$LOG_FILE;
system MYSQL_CMD -e "show master status;"|tail -l >>$LOG_FILE;
system ${MYSQL_DUMP} | gzip >$DATA_FILE;
EOF
$MYSQL_CMD -e "unlock tables;"


#---- slave 从库 ----#
#!/bin/bash
MYUSER="root"
MYPASS="123456"
MYSOCK=/data/3306/mysql.sock
MAIN_PATH=/server/backup
LOG_FILE=${MAIN_PATH}/logs_`date +%F`.log
DATA_FILE=${MAIN_PATH}/backup_`date +%F`.sql.gz
MYSQL_PATH=/usr/local/mysql/bin
MYSQL_CMD="${MYSQL_PATH}/mysql -u$MYUSER -p$MYPASS -S $MYSOCK"
#recover
cd ${MAIN_PATH}
gzip -d backup_`date +%F`.sql.gz
$MYSQL_CMD<backup_`date +%F`.sql
#config slave (由于是全备所以不需要加pos位置)
cat |$MYSQL_CMD<< EOF
CHANGE MASTER TO
MASTER_HOST='10.0.0.1',
MASTER_PORT="3306",
MASTER_USER='rep',
MASTER_PASSWORD='oldboy123',
EOF
$MYSQL_CMD -e "start slave;"
$MYSQL_CMD -e "show slave status\G" |egrep "IO_Runing|SQL_Runing" >$LOG_FILE
mail -s "mysql slave result" [email protected] <$LOG_FILE