Python 数据库备份脚本(邮件通知+日志记录)

文章来源:http://www.cnblogs.com/wubz/archive/2013/02/28/2936789.html

#dbbackup.py
#!/usr/bin/python 
#coding:utf-8 
 
import subprocess 
import time 
import os 
import sys 
import sendEmail 
import getip 
import logging  
  
#create logger  
logger = logging.getLogger("dbbackup")  
logger.setLevel(logging.DEBUG)  
#create console handler and set level to error  
ch = logging.StreamHandler()  
ch.setLevel(logging.ERROR)  
#create file handler and set level to debug  
fh = logging.FileHandler("dbbackup.log")  
fh.setLevel(logging.DEBUG)  
#create formatter  
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")  
#add formatter to ch and fh  
ch.setFormatter(formatter)  
fh.setFormatter(formatter)  
#add ch and fh to logger  
logger.addHandler(ch)  
logger.addHandler(fh)  
  
 
mail_to_list = ['lihuipeng@xxx.com',] 
 
def backup(user='root', password='123456', host='localhost', dbname='mysql'): 
    start_time = time.clock() 
    ip = getip.get_ip_address('eth0') 
    today = time.strftime("%Y%m%d", time.localtime()) 
    backup_dir = '/data/dbbackup/%s' % today 
    if not os.path.isdir(backup_dir): 
        os.makedirs(backup_dir) 
    os.chdir(backup_dir) 
    cmd = "/usr/local/mysql/bin/mysqldump --opt -u%s -p%s -h%s %s | gzip > %s-%s-%s.sql.gz" \ 
                % (user,password,host,dbname,today,ip,dbname) 
    logger.debug(dbname + ':' + cmd) 
    result = subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) 
    content = result.stdout.read() 
    if content: 
        logger.error(dbname + ':' + content) 
        subject = "%s - %s backup error" % (ip,dbname) 
        sendEmail.send_mail(mail_to_list,subject,content) 
    end_time = time.clock() 
    use_time = end_time - start_time 
    logger.debug(dbname + " backup use: %s" % use_time) 
     
def help(): 
    print '''''Usage: %s dbname'''  % sys.argv[0] 
    sys.exit(1) 
         
if __name__ == "__main__": 
    if len(sys.argv) != 2: 
        help() 
    backup(dbname=sys.argv[1]) 
     
     
复制代码

 

复制代码
复制代码
#sendEmail.py
#!/usr/bin/python 
#coding:utf-8 
 
import smtplib 
from email.mime.text import MIMEText 
 
mail_to_list = ['xxxxxx@qq.com',] 
mail_host = 'smtp.163.com' 
mail_user = 'lihuipeng007' 
mail_pass = 'xxxxxxx' 
mail_postfix = '163.com' 
 
def send_mail(to_list,subject,content): 
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">" 
    msg = MIMEText(content) 
    msg['Subject'] = subject 
    msg['From'] = me 
    msg['to'] = ";".join(mail_to_list) 
     
    try: 
        s = smtplib.SMTP() 
        s.connect(mail_host) 
        s.login(mail_user,mail_pass) 
        s.sendmail(me,to_list,msg.as_string()) 
        s.close() 
        return True 
    except Exception,e: 
        print str(e) 
        return False 
     
if __name__ == "__main__": 
    if send_mail(mail_to_list, 'Test for python_mail', "aaaaaaaaaaaaaaa"): 
        print "send success!" 
    else: 
        print "send fail!"  
复制代码
复制代码
#getip.py
#!/usr/bin/python 
#coding:utf-8 
 
import socket 
import fcntl 
import struct 
def get_ip_address(ifname): 
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    return socket.inet_ntoa(fcntl.ioctl( 
        s.fileno(), 
        0x8915,  # SIOCGIFADDR 
        struct.pack('256s', ifname[:15]) 
    )[20:24]) 
     
if __name__ == "__main__": 
    print get_ip_address('eth0') 
    print get_ip_address('lo') 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值