公司有一台静态页面展示服务器仅供给客户展示我们做的项目,当时买的时候是最低配,也就是磁盘空间为20G的系统盘,考虑到代码量很小所以没有另加磁盘,后来项目多了,就写了个crontab 定时备份目录。

就这样,这台服务器稳健运行着。过了大半年,突然有一天挂在该服务器上的wordpress登陆不了了。找了好久找不到问题。不经意之间看来下磁盘利用率才发现了问题。

使用命令:

df -h

发现磁盘/dev/xvdal没空间了!

导致缓存与session无法保存。想起来可能是备份目录导致的,10几个项目,一个项目10Mb左右每天备份一次,半年时间:10*10*150=15GB(项目是逐渐加进去的),删除某一天的备份,重新登录wordpress真给登录上去了。

如果知道了是备份的问题,定期删除备份文件也行。但爱折腾的人肯定是闲不下来的。干嘛要备份到服务器中呢,完全可以打包把备份文件通过邮件进行备份呀。就这样定时Python备份目录发送邮件功能变成了“现实”。

一.crontab定时

crontab  -e
  * * *   /root/crontab-save-code.py                           #每天凌晨1点30分执行备份目录 

二.打包目录

# 压缩目录toZip
def DirToZip(dirname, zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else:
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name)) try:
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
try: # 异常出现在文件名为中文
zf.write(tar, arcname)
except:
zf.write(tar, repr(arcname)[1:-1])
zf.close()
return True
except Exception as e:
return False

生成ZIP压缩文件时有个问题,压缩到一半报错:

'utf-8' codec can't encode character '\udcb8' in position 41: surrogates not allowed

编码的问题,文件使用中文名导致的,参考:http://python3-cookbook.readthedocs.io/zh_CN/latest/c05/p15_printing_bad_filenames.html

三.发送带附件的邮件

# 发送邮件
def sendMail():
print(ZipName)
# 输入Email地址和口令:
from_addr = 'admin@****.com'
password = ''
# 输入收件人地址:
to_addr = '*****@163.com'
# 输入SMTP服务器地址:
smtp_server = 'smtp.exmail.qq.com' # 邮件对象:
msg = MIMEMultipart()
msg['From'] = _format_addr('自动备份项目代码 <%s>' % from_addr)
msg['To'] = _format_addr('Web管理员 <%s>' % to_addr)
msg['Subject'] = Header('来自SMTP-定时备份……', 'utf-8').encode() # 邮件正文是MIMEText:
msg.attach(MIMEText('自动备份项目代码 file...', 'plain', 'utf-8')) # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open(filePath, 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image', 'png', filename='test.png')
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename=ZipName)
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
try:
server = smtplib.SMTP(smtp_server, 25)
# server.set_debuglevel(1)
server.login(from_addr, password)
a = server.sendmail(from_addr, [to_addr], msg.as_string())
return True
except Exception:
return False

四. 发送成功,删除压缩包

# 删除文件
def delFile():
if os.path.exists(filePath):
os.remove(filePath)

经测试,在windows很开就收到了,但上传到服务器又报错了:

/usr/bin/python^M: bad interpreter: No such file

是因为windows行结尾和linux行结尾标识不同造成的。使用notepad++把文件转换为UNIX格式。

完整代码:

#!/usr/bin/python
# coding=utf-8
import os, os.path
import zipfile
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
import datetime
import os ZipName = datetime.datetime.now().strftime('%Y-%m-%d@%H.%M') + '.zip'
filePath = "/home/wwwroot/tools/backup/" + ZipName # 压缩目录toZip
def DirToZip(dirname, zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else:
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name)) try:
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
try: # 异常出现在文件名为中文
zf.write(tar, arcname)
except:
zf.write(tar, repr(arcname)[1:-1])
zf.close()
return True
except Exception as e:
return False # 格式字符串
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr)) # 发送邮件
def sendMail():
print(ZipName)
# 输入Email地址和口令:
from_addr = 'admin@****.com'
password = ''
# 输入收件人地址:
to_addr = '****@163.com'
# 输入SMTP服务器地址:
smtp_server = 'smtp.exmail.qq.com' # 邮件对象:
msg = MIMEMultipart()
msg['From'] = _format_addr('自动备份项目代码 <%s>' % from_addr)
msg['To'] = _format_addr('Web管理员 <%s>' % to_addr)
msg['Subject'] = Header('来自SMTP-定时备份……', 'utf-8').encode() # 邮件正文是MIMEText:
msg.attach(MIMEText('自动备份项目代码 file...', 'plain', 'utf-8')) # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open(filePath, 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image', 'png', filename='test.png')
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename=ZipName)
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
try:
server = smtplib.SMTP(smtp_server, 25)
# server.set_debuglevel(1)
server.login(from_addr, password)
a = server.sendmail(from_addr, [to_addr], msg.as_string())
return True
except Exception:
return False # 删除文件
def delFile():
if os.path.exists(filePath):
os.remove(filePath) if __name__ == '__main__':
zipfile = DirToZip(r'/home/wwwroot/www', filePath)
if zipfile:
sending = sendMail()
if sending:
delFile()

成功发送邮件:

Python +crontab定时备份目录发送邮件的更多相关文章

  1. Linux下使用crontab定时备份日志

    上周学习了Linux,其中有使用crontab定时备份日志的内容,现把主要步骤记录如下: 首先需要备份的日志的源目录位于/opt/lampp/logs/access_log 备份到/tmp/logs下 ...

  2. linux下使用crontab定时备份MYSQL数据库的方法:

    摘要 linux下使用crontab定时备份MYSQL数据库的方法: 只需按照下面3步做,一切都在你的掌控之下: 第一步:在服务器上配置备份目录代码: ------------------------ ...

  3. MySQL定时备份之使用Linux下的crontab定时备份实例

    这篇文章主要介绍了使用Linux下的crontab进行MySQL定时备份的例子,需要的朋友可以参考下   复制代码代码如下: ##################################### ...

  4. Linux下MySQL备份以及crontab定时备份

    1. 备份某个数据库 ################################################################## # 备份某个数据库 ############ ...

  5. MySQL使用crontab定时备份不执行问题

    在使用crontab定时备份数据库时,发现并没有执行备份命令. 下面是定时备份的代码: 30 1 * * * /usr/local/mysql/bin/mysqldump --defaults-ext ...

  6. 使用python脚本定时备份web网站

    #!/usr/bin/env python #-*- coding: utf-8 -*- import os import time # 备份的指定目录 source = ['/data/www/Ad ...

  7. Gitlab备份,Crontab定时备份

    1:Gitlab备份非常简单,只需要一条命令就可以创建完整的备份 gitlab-rake gitlab:backup:create 使用以上命令,就相当于在/var/opt/gitlab/backup ...

  8. Linux 使用crontab定时备份Mysql数据库

    项目中数据库的数据是至关重要的!在实际项目中,遇到有客户机房断电导致数据库数据丢失的问题,又因为备份容灾不及时,导致部分数据恢复不了,而刚好这部分丢失的数据对于客户来说又是至关重要的,那么怎么办呢?盲 ...

  9. python - 代码练习 - 备份目录/文件(windos环境)

    备份目录/文件 import zipfile import os,datetime class beifen(object): def __init__(self,files,new_files,co ...

随机推荐

  1. 个人对B/S项目的一些理解(三)--Servlet与Strust

    以下是我自工作以来,结合对C/S项目的认知,对B/S项目的一些理解. 如有不足或者错误,请各位指正.   由于个人一开始入门时是ASP.NET MVC,是一个比较完善.完整的框架,下面仅对JAVA的w ...

  2. 使用Python解析JSON数据

    使用Python解析百度API返回的JSON格式的数据 # coding:utf-8 # !/usr/bin/env python import matplotlib.pyplot as plt fr ...

  3. Web API系列(一)设计经验与总结

    在移动互联网的时代, Web服务已经成为了异构系统之间的互联与集成的主要手段,各种 Web服务几乎都采用REST风格的Web Api来构建. 通过Http协议的形式来. 以Get/Post方式发送请求 ...

  4. python 生成器等语法

    生成器 调用生成器函数,不会执行生成器函数中的代码,而是返回一个对象,  这个对象是生成器(可用type()函数判断这个对象类型),  如果要运行生成器函数中的代码, 需要调用 next()方法,   ...

  5. adobe premiere pro cc2015.0已停止工作 解决办法

    adobe premiere pro cc2015.0已停止工作 一直报错 解决办法就是: 删除我的电脑  我的饿文档下的 Adobe下的Premiere Pro文件夹 现象就是怎么重新安装都不管用P ...

  6. jQuery导入Eclipse后报错解决方法

         使用Eclipse 3.7及以上版本时,工程中加入jquery.min.js文件,发现该文件出现错误提示(红×),但使用Eclipse 3.7以前的版本就不会出现这种提示.是因为Eclips ...

  7. Find and delete duplicate files

    作用:查找指定目录(一个或多个)及子目录下的所有重复文件,分组列出,并可手动选择或自动随机删除多余重复文件,每组重复文件仅保留一份.(支持文件名有空格,例如:"file  name" ...

  8. C#高级编程笔记2016年10月12日 运算符重载

    1.运算符重载:运算符重重载的关键是在对象上不能总是只调用方法或属性,有时还需要做一些其他工作,例如,对数值进行相加.相乘或逻辑操作等.例如,语句if(a==b).对于类,这个语句在默认状态下会比较引 ...

  9. airflow 部署

    环境 : ubuntu 14.04 LTS python 2.7 script: 设置环境变量: export AIRFLOW_HOME=~/airflow 安装相关依赖包: sudo apt-get ...

  10. html5 json的新用法

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...