Python 数据库备份脚本(邮件通知+日志记录)
#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')