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

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介:

 在原来的基础上添加了日志管理模块,输出屏幕的同时也记录文件,方便查看日志信息:

dbbackup.py

 
  1. #!/usr/bin/python 
  2. #coding:utf-8 
  3.  
  4. import subprocess 
  5. import time 
  6. import os 
  7. import sys 
  8. import sendEmail 
  9. import getip 
  10. import logging  
  11.   
  12. #create logger  
  13. logger = logging.getLogger("dbbackup")  
  14. logger.setLevel(logging.DEBUG)  
  15. #create console handler and set level to error  
  16. ch = logging.StreamHandler()  
  17. ch.setLevel(logging.ERROR)  
  18. #create file handler and set level to debug  
  19. fh = logging.FileHandler("dbbackup.log")  
  20. fh.setLevel(logging.DEBUG)  
  21. #create formatter  
  22. formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")  
  23. #add formatter to ch and fh  
  24. ch.setFormatter(formatter)  
  25. fh.setFormatter(formatter)  
  26. #add ch and fh to logger  
  27. logger.addHandler(ch)  
  28. logger.addHandler(fh)  
  29.   
  30.  
  31. mail_to_list = ['lihuipeng@xxx.com',] 
  32.  
  33. def backup(user='root', password='123456', host='localhost', dbname='mysql'): 
  34.     start_time = time.clock() 
  35.     ip = getip.get_ip_address('eth0'
  36.     today = time.strftime("%Y%m%d", time.localtime()) 
  37.     backup_dir = '/data/dbbackup/%s' % today 
  38.     if not os.path.isdir(backup_dir): 
  39.         os.makedirs(backup_dir) 
  40.     os.chdir(backup_dir) 
  41.     cmd = "/usr/local/mysql/bin/mysqldump --opt -u%s -p%s -h%s %s | gzip > %s-%s-%s.sql.gz" \ 
  42.                 % (user,password,host,dbname,today,ip,dbname) 
  43.     logger.debug(dbname + ':' + cmd) 
  44.     result = subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) 
  45.     content = result.stdout.read() 
  46.     if content: 
  47.         logger.error(dbname + ':' + content) 
  48.         subject = "%s - %s backup error" % (ip,dbname) 
  49.         sendEmail.send_mail(mail_to_list,subject,content) 
  50.     end_time = time.clock() 
  51.     use_time = end_time - start_time 
  52.     logger.debug(dbname + " backup use: %s" % use_time) 
  53.      
  54. def help(): 
  55.     print '''''Usage: %s dbname'''  % sys.argv[0
  56.     sys.exit(1
  57.          
  58. if __name__ == "__main__"
  59.     if len(sys.argv) != 2
  60.         help() 
  61.     backup(dbname=sys.argv[1]) 
  62.      
  63.      
  64.      

sendEmail.py

 
  1. #!/usr/bin/python 
  2. #coding:utf-8 
  3.  
  4. import smtplib 
  5. from email.mime.text import MIMEText 
  6.  
  7. mail_to_list = ['xxxxxx@qq.com',] 
  8. mail_host = 'smtp.163.com' 
  9. mail_user = 'lihuipeng007' 
  10. mail_pass = 'xxxxxxx' 
  11. mail_postfix = '163.com' 
  12.  
  13. def send_mail(to_list,subject,content): 
  14.     me = mail_user+"<"+mail_user+"@"+mail_postfix+">" 
  15.     msg = MIMEText(content) 
  16.     msg['Subject'] = subject 
  17.     msg['From'] = me 
  18.     msg['to'] = ";".join(mail_to_list) 
  19.      
  20.     try
  21.         s = smtplib.SMTP() 
  22.         s.connect(mail_host) 
  23.         s.login(mail_user,mail_pass) 
  24.         s.sendmail(me,to_list,msg.as_string()) 
  25.         s.close() 
  26.         return True 
  27.     except Exception,e: 
  28.         print str(e) 
  29.         return False 
  30.      
  31. if __name__ == "__main__"
  32.     if send_mail(mail_to_list, 'Test for python_mail'"aaaaaaaaaaaaaaa"): 
  33.         print "send success!" 
  34.     else
  35.         print "send fail!"  

getip.py

 
  1. #!/usr/bin/python 
  2. #coding:utf-8 
  3.  
  4. import socket 
  5. import fcntl 
  6. import struct 
  7. def get_ip_address(ifname): 
  8.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
  9.     return socket.inet_ntoa(fcntl.ioctl( 
  10.         s.fileno(), 
  11.         0x8915,  # SIOCGIFADDR 
  12.         struct.pack('256s', ifname[:15]) 
  13.     )[20:24]) 
  14.      
  15. if __name__ == "__main__"
  16.     print get_ip_address('eth0'
  17.     print get_ip_address('lo'
本文转自运维笔记博客51CTO博客,原文链接 http://blog.51cto.com/lihuipeng/1061307如需转载请自行联系原作者

lihuipeng
相关文章
|
29天前
|
SQL 存储 关系型数据库
|
29天前
|
存储 关系型数据库 MySQL
|
29天前
|
存储 SQL 关系型数据库
|
6天前
|
存储 SQL Oracle
关系型数据库Oracle归档日志备份
【7月更文挑战第19天】
28 5
|
17天前
|
消息中间件 JSON 自然语言处理
python多进程日志以及分布式日志的实现方式
python日志在多进程环境下的问题 python日志模块logging支持多线程,但是在多进程下写入日志文件容易出现下面的问题: PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。 也就是日志文件被占用的情况,原因是多个进程的文件handler对日志文件进行操作产生的。
|
20天前
|
Python
Python编程实战:利用闭包与装饰器优化日志记录功能
【7月更文挑战第7天】Python的闭包和装饰器简化了日志记录。通过定义如`log_decorator`的装饰器,可以在不修改原函数代码的情况下添加日志功能。当@log_decorator用于`add(x, y)`函数时,调用时自动记录日志。进一步,`timestamp_log_decorator`展示了如何创建特定功能的装饰器,如添加时间戳。这些技术减少了代码冗余,提高了代码的可维护性。
19 1
|
26天前
|
存储 关系型数据库 MySQL
|
1月前
|
SQL 运维 关系型数据库
|
14天前
|
Unix Python
Python代码示例:使用`syslog`模块进行日志记录
Python代码示例:使用`syslog`模块进行日志记录
|
29天前
|
SQL Java 数据库连接
使用Python通过JDBC操作数据库(达梦数据库)
使用Python通过JDBC操作数据库(达梦数据库)
69 0