今天用Python写了一个数据库备份脚本,备份失败会用邮件的形式通知系统管理员,感觉还行:
- #!/usr/bin/python
- #coding:utf-8
- import subprocess
- import time
- import os
- import sys
- import sendEmail
- import getip
- mail_to_list = ['lihuipeng007@51cto.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)
- result = subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
- content = result.stdout.read()
- if content:
- print "Dump error at %s" % 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
- print "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])
发送邮件的PY接口:
sendEmail.py
- #!/usr/bin/python
- #coding:utf-8
- import smtplib
- from email.mime.text import MIMEText
- mail_to_list = ['lihuipeng007@51cto.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!"
获取本机IP地址的PY接口:
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')