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

手册/FAQ (400) 2015-10-28 10:07:09

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

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') 

 

 

THE END