日期:2014-05-16  浏览次数:20870 次

轻松实现MySQL自动备份脚本
以下脚本实现每天自动备份,保存最近一周的所有全备份数据及上传至FTP备份,并且压缩减少磁盘空间,可以直接修改IP,密码等信息后,直接拿来用
有问题请回贴跟踪,欢迎拍砖!!!!

复制内容到剪贴板代码:
#!/bin/bash
# Written by Mpfei at 20090622
# Change your dbname of ucstarserver ,please define the following parameters
# Make sure the Script attribution is : 700
# Usage: #chmod 700 ucstarbackup.sh
# Modfify your database parameters #
##########################################################
DBUser=root
DBPasswd=qingqi
DBHost="192.168.1.160"
DBPort=3306
#Define this PATH ,for example:
#BackupPath=/home/backup
BackupPath=/home/backup
LogPath=/var/log/
LogFile=/var/log/mysqldb.log
#default mysql path
DBPath=/var/lib/mysql/
BackupMethod=mysqldump
#########################################################
#FTP server parameters,and make sure ftpserver remote directory exists
#For example: ucstar,wikidb,egroupware,discuz
FTPHost=192.168.1.160
FTPUser=username
FTPPasswd=123
Ftpath=/backup/
#########################################################

if [ -f $LogFile ]; then
   echo "The logfile is $LogFile "
   else
   touch "$LogFile"
   echo "Generate a new log file and locate $LogFile"
   fi
  
   echo "----------------------------------------------" >> $LogFile
   echo $(date +"%y-%m-%d %H:%M:%S") >> $LogFile
   echo "----------------------------------------------" >> $LogFile
#
#define a array of dbname and  backup those database
declare -a DBName
DATABASE=("ucstar" "roller" "discuz" "wikidb" "egroupware")
#
for DBName in ${DATABASE[@]}; do 
#
#Define file
NewFile="$DBName"db$(date +%y%m%d).tar.gz
DumpFile="$DBName"db$(date +%y%m%d).sql
OldFile="$DBName"db$(date +%y%m%d --date='7 days ago').tar.gz
#

echo "The latest backup file locate $BackupPath/$DBName/$NewFile"

cd "$BackupPath"
  if [ -d $DBName ]; then
     cd "$DBName"
     else
     mkdir -p "$DBName"
     cd "$DBName"
     echo "$DBName diretory no exists,mkdir the directory " >> $LogFile
     echo "$DBName diretory no exists,mkdir the directory "
   fi
    

if [ -f $NewFile ]; then
  echo "[$BackupPath/$DBName/$NewFile]The latest Backup File is exists,Cancel Backup" >> $LogFile
  echo "The latest backup file exists,Cancel!"
  else
  case $BackupMethod in
  mysqldump)
    if [ -z $DBPasswd ]; then
      mysqldump -u "$DBUser" -h "$DBHost" -P "$DBPort" --opt "$DBName" > $DumpFile
      else
      mysqldump -u "$DBUser" -p"$DBPasswd" -h "$DBHost" -P "$DBPort" --opt "$DBName" > $DumpFile
     fi
    if [ ! -s $DumpFile ]; then
       echo "-----Export $DBName new database file failure------------"
       echo "Maybe $DBHost can't connect or $DBName database isn't exists"
       echo "-----Export $DBName new database file failure------------" >> $LogFile
       echo "Maybe $DBHost can't connect or $DBName database isn't exists" >> $LogFile
       echo "Do nothing"
       echo "Do nothing." >> $LogFile
       else
       tar -c