本文共 2598 字,大约阅读时间需要 8 分钟。
在网上看了几个脚本根据网上的稍微修改了下,稍微更准确了点,就是缺少记录日志的功能,还没想好怎么写,后续添加
#!/bin/bash
#做大备份数量Backup_Max_Files=20#数据库备份目录WORKING_DIR=$(dirname "$0")export WORKING_DIR=$(cd -P "$WORKING_DIR"/ > /dev/null; pwd)#数据库IP地址、帐号、密码DB_Host="XXXXXXX"DB_User="XXXXXX"DB_Password="XXXXXXX"#需要备份的数据库Databases=("mysql""zabbix")#==========
echo "###########Bash Shell MySql Databases Backup Tools!"#定义变量=当前日期
Date_Time=$(date +%F)#定义备份文件前缀
BackDataFile=zhang"${Date_Time}"cd $WORKING_DIRmkdir $BackData_File#统计需要备份数据库的个数count=0while [ "x${Databases[count]}" != "x" ]docount=$((count + 1))echo "Databases=$count"doneecho "[+] ${count} The database is about to be backed up"for Databases in ${Databases[@]}
doecho "[+] MySql-backing up: ${Databases}"echo -n " MySql Backup Start: "echo $(date +"%Y-%m-%d %H:%M:%S")#使用Mysqdump工具进行逻辑备份(全备)并使用邮件脚本发送成功失败提醒if $(mysqldump -h${DB_Host} -u${DB_User} -p${DB_Password} --single-transaction --flush-logs mysql > ${BackData_File}/${Databases}.sql )thenecho " Success OK!: Mysql database backup success!"python /root/jiaoben/mail.py "y@163.com" "${Databases}数据库备份成功" "${Databases}>数据库备份成功"elseecho " Error NO!: Failure of MySQL database backup!"#python /root/jiaoben/mail.py "y@163.com" "${Databases}数据库备份失败" "${Databases}>数据库备份失败请查看"fiecho -n "Backup success: "echo $(date +"%Y-%m-%d %H:%M:%S")doneechoecho "[+] Packaging and compressing folders with Tar ...."#使用tar命令打包并压缩生成的数据库文件cd $WORKING_DIRtar -cv ${BackData_File} | bzip2 > ${BackData_File}.tar.bz2 && rm -rf ${BackData_File}#删除n天以前备份的数据文件echo "[+] Delete over time database backup files ...."
find $WORKINGDIR -name "zhang*.tar.bz2" -mtime +${Backup_Max_Files} -exec rm -rf {} \;#find $WORKINGDIR -name "zhang*.tar.bz2" -mtime +${Backup_Max_Files} -exec ls {} \;
后补:邮件报警脚本(网络版,已测试可以使用没有问题)
#!/usr/bin/pythoncoding=utf-8#测试方法:python 5.py XXXXX@163.com test test
#能正常发送邮件说明成功 import smtplibimport sysfrom email.mime.text import MIMETextclass send_mail():mail_user="XXXXXX@163.com"
br/>mail_host="smtp.163.com"mail_user="XXXXXX@163.com"#此出不是登录密码。而是开头smtp的登录口令mail_pass="XXXXXx"mail_postfix="163.com"def init(self,sub,content):def sendMessage(self,user): self.msg['To'] = ";".join(user) try: s = smtplib.SMTP_SSL(host=self.mail_host,port=465) s.login(self.mail_user,self.mail_pass) s.sendmail(self.me, user, self.msg.as_string())
#发送邮件
s.close()except Exception, e:print str(e)if name == 'main':
mailto_list=[]mailto_list.append(sys.argv[1])s = send_mail(sys.argv[2],sys.argv[3])s.sendMessage(mailto_list)转载于:https://blog.51cto.com/bosszhang/2059523