定时备份mysql数据库到邮箱

2011年3月3日 | 分类: Linux | 标签: , , , , , , , , , ,

2011.3.19更新:添加压缩分卷支持以及将msmtp分离出独立安装脚本
2011.3.11更新:添加可选项,给压缩文件加设密码
特性:自动备份mysql数据库,自动发送备份到邮箱,定期删除服务上超过5天的备份。
已经用在我服务器上了。

wget http://www.yishanhome.com/wp-content/uploads/2011/03/bakup_mysql_send_email.sh;sh bakup_mysql_send_email.sh


Dropbox启用邮件接收文件申请地址http://sendtodropbox.com/

bakup_mysql_send_email.sh 代码如下

#!/bin/bash
if [ $(id -u) != "0" ]; then
    printf "Error: You must be root to run this tool!\n"
    exit 1
fi
clear
printf "
#This is a Shell-Based tool of Backup mysql database
# Author: yishan
# Website: http://www.yishanhome.com
"
  echo "Command is running, please wait....."
  ret=`rpm -qa|grep mutt|wc -l`
if [ $ret = "0" ] ; then
  echo "install mutt"
    yum install -y mutt
  fi
  ret=`service crond stop|wc -l`
if [ $ret = "0" ] ; then
  echo "install crond"
    yum install -y vixie-cron
  fi
echo "Command is ready, press any key to continue....."
read anykey
workdir=/root
outdir=/root/bak_mysql
DUMP=mysqldump
ip=`hostname -i`
zippws=yishanhome
echo "Please input the work directory:"
  read -p "(Current directory: $workdir):" workdir
  if [ "$workdir" = "" ]; then
    workdir=/root
  fi
echo "Please input your backup file directory path:"
  read -p "(Current directory: $outdir):" outdir
  if [ "$outdir" = "" ]; then
   outdir="/root/bak_mysql"
  fi
echo "Please input the mysqldump location:"
  read -p "(Current location: $DUMP):" DUMP
  if [ "$DUMP" = "" ]; then
   DUMP=mysqldump
  fi
 input_DB_NAME()
{
  read -p "Please input the Backup mysql database name:" DB_NAME
  if [ "$DB_NAME" = "" ]; then
  input_DB_NAME
  fi
}
input_DB_USER()
{
  read -p "Please input the mysql database user:" DB_USER
  if [ "$DB_USER" = "" ]; then
  input_DB_USER
  fi
}
input_DB_PASS()
{
  read -p "Please input the mysql database password:" DB_PASS
  if [ "$DB_PASS" = "" ]; then
  input_DB_PASS
  fi
}
input_mailsend()
{
  read -p "Please input the email address stored backup files:" mailsend
  if [ "$mailsend" = "" ]; then
  input_mailsend
  fi
}
input_DB_NAME
input_DB_USER
input_DB_PASS
input_mailsend
echo -e '\033[0;31;1mPlease input ZIP Password:\033[0m'
  read -p "(default : $zippws):" zippws
    if [ "$zippws" = "" ]; then
    zippws=yishanhome
  fi
mkdir -p $outdir
cat > $workdir/bak_mysql.sh < \$OUT_SQL
tar -czf \$TAR_SQL ./\$OUT_SQL
zip -P $zippws -r \$ZIP_SQL \$TAR_SQL
rm -f \$OUT_SQL \$TAR_SQL
mkdir tmp
cd tmp
split -b 5m -a 3 -d $outdir/\$ZIP_SQL \$ZIP_SQL.part
for file in *
do
echo "\$ZIP_SQL" | mutt -s "\$ZIP_SQL" $mailsend -a \$file
sleep 30s
done
cd $outdir
rm -rf $outdir/tmp
find ./ -name "mysql*" -type f -mtime +5 -exec rm {} \;
EOF
 
chmod 700 $workdir/bak_mysql.sh
chkconfig --level 35 crond on
echo "5 3 * * * root $workdir/bak_mysql.sh" >>/etc/crontab
service crond restart
cd $workdir
$workdir/bak_mysql.sh
目前还没有任何评论.

返回顶部