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

linux下Mysql自动备份脚本
将下列保存为一个.sh 文件
然后把上面的脚本文件上传到服务器,可放到 linux 目录下
修改 脚本的 为可执行文件   命令  chmod +x filename ; 
先用vi打开系统的cronntab:  vi /etc/crontab, 你将看到下面一段文字
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
0  1 * * * root /home/filename.sh


看到最后一行了吗? 这就是在每天的1时0分执行 /home/filename.sh 脚本,这个时间你可以自由设定,执行次数也可以自由设定

添加后 保存就 可以了

#!/bin/bash 
#This is a ShellScript For Auto DB Backup 
#Powered by aspbiz 
#2004-09 

#Setting 
#设置数据库名,数据库登录名,密码,备份路径,日志路径,数据文件位置,
#以及备份方式 
#默认情况下备份方式是tar,还可以是mysqldump,mysqldotcopy 
#默认情况下,用root(空)登录mysql数据库,备份至/root/dbxxxxx.tgz 
DBName=pets_center_v1	
DBUser=root
DBPasswd=
BackupPath=/home/back/db/
LogFile=/home/back/dbbackup.log
DBPath=/var/lib/mysql/ 
#BackupMethod=mysqldump 
BackupMethod=mysqlhotcopy 
#BackupMethod=tar 
#Setting End 


NewFile="$BackupPath"$DBName-$(date +%y%m%d).tgz 
DumpFile="$BackupPath"$DBName-$(date +%y%m%d).sql 
OldFile="$BackupPath"$DBName-$(date +%y%m%d --date='30 days ago').tgz 

echo "-------------------------------------------" >> $LogFile 
echo $(date +"%y-%m-%d %H:%M:%S") >> $LogFile 
echo "--------------------------" >> $LogFile 
#Delete Old File 
if [ -f $OldFile ] 
then 
   rm -f $OldFile >> $LogFile 2>&1 
   echo "[$OldFile]Delete Old File Success!" >> $LogFile 
else 
   echo "[$OldFile]No Old Backup File!" >> $LogFile 
fi 

if [ -f $NewFile ] 
then 
   echo "[$NewFile]The Backup File is exists,Can't Backup!" >> $LogFile 
else 
   case $BackupMethod in 
   mysqldump) 
      if [ -z $DBPasswd ] 
      then 
         mysqldump -u $DBUser --opt $DBName > $DumpFile 
      else 
         mysqldump -u $DBUser -p$DBPasswd --opt $DBName > $DumpFile 
      fi 
      tar czvf $NewFile $DumpFile >> $LogFile 2>&1 
      echo "[$NewFile]Backup Success!" >> $LogFile 
      rm -rf $DumpFile 
      ;; 
   mysqlhotcopy) 
      rm -rf $DumpFile 
      mkdir $DumpFile 
      if [ -z $DBPasswd ] 
      then 
         mysqlhotcopy -u $DBUser $DBName $DumpFile >> $LogFile 2>&1 
      else 
         mysqlhotcopy -u $DBUser -p $DBPasswd $DBName $DumpFile >>$LogFile 2>&1 
      fi 
      tar czvf $NewFile $DumpFile >> $LogFile 2>&1 
      echo "[$NewFile]Backup Success!" >> $LogFile 
      rm -rf $DumpFile 
      ;; 
   *) 
      /etc/init.d/mysqld stop >/dev/null 2>&1 
      tar czvf $NewFile $DBPath$DBName >> $LogFile 2>&1 
      /etc/init.d/mysqld start >/dev/null 2>&1 
      echo "[$NewFile]Backup Success!" >> $LogFile 
      ;; 
   esac 
fi 

echo "-------------------------------------------" >> $LogFile