不管怎样,数据在别人的服务器上,备份必不可少。
不想每次手动,加上备份数据在vps上是没有意义的,上传到百度云或者微云也麻烦,还好数据库不大,直接通过邮件附件备份就行。
直接上代码:
#!/usr/bin/python2.7
# _*_ coding: utf-8 _*_
# By:www.52our.com
import urllib,urllib2,smtplib,datetime,os
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
mail_host = "smtp.qq.com"
mail_user = "xxx@qq.com"
mail_pass = "密钥"
sender = 'xxx@qq.com'
receivers = ','.join(['xxx@qq.com'])
dbfile = '文件路径'
with os.popen('md5sum '+dbfile) as r:
md5 = r.read()
msg = MIMEMultipart()
msg['Subject'] = Header('BLOG数据库备份' + str(datetime.date.today()),'utf-8')
msg['From'] = sender
msg['To'] = receivers
mailtext = MIMEText(str(datetime.date.today())+'博客数据库备份,MD5:'+md5,'plain','utf-8')
msg.attach(mailtext)
with open(dbfile,'rb') as f:
annex = MIMEApplication(f.read())
annex.add_header('Content-Disposition','attachment',filename='附件名')
msg.attach(annex)
try:
smtpObj = smtplib.SMTP_SSL()
smtpObj.connect(mail_host,465)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,receivers,msg.as_string())
print "success"
except smtplib.SMTPException,ex:
print "Error",ex
设置好定时,每周在邮箱接收备份数据就行。有些邮箱的附件有保存时间限制,在限制时间内进行新备份即可。