Python +crontab定时备份目录发送邮件
公司有一台静态页面展示服务器仅供给客户展示我们做的项目,当时买的时候是最低配,也就是磁盘空间为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定时备份目录发送邮件的更多相关文章
- Linux下使用crontab定时备份日志
上周学习了Linux,其中有使用crontab定时备份日志的内容,现把主要步骤记录如下: 首先需要备份的日志的源目录位于/opt/lampp/logs/access_log 备份到/tmp/logs下 ...
- linux下使用crontab定时备份MYSQL数据库的方法:
摘要 linux下使用crontab定时备份MYSQL数据库的方法: 只需按照下面3步做,一切都在你的掌控之下: 第一步:在服务器上配置备份目录代码: ------------------------ ...
- MySQL定时备份之使用Linux下的crontab定时备份实例
这篇文章主要介绍了使用Linux下的crontab进行MySQL定时备份的例子,需要的朋友可以参考下 复制代码代码如下: ##################################### ...
- Linux下MySQL备份以及crontab定时备份
1. 备份某个数据库 ################################################################## # 备份某个数据库 ############ ...
- MySQL使用crontab定时备份不执行问题
在使用crontab定时备份数据库时,发现并没有执行备份命令. 下面是定时备份的代码: 30 1 * * * /usr/local/mysql/bin/mysqldump --defaults-ext ...
- 使用python脚本定时备份web网站
#!/usr/bin/env python #-*- coding: utf-8 -*- import os import time # 备份的指定目录 source = ['/data/www/Ad ...
- Gitlab备份,Crontab定时备份
1:Gitlab备份非常简单,只需要一条命令就可以创建完整的备份 gitlab-rake gitlab:backup:create 使用以上命令,就相当于在/var/opt/gitlab/backup ...
- Linux 使用crontab定时备份Mysql数据库
项目中数据库的数据是至关重要的!在实际项目中,遇到有客户机房断电导致数据库数据丢失的问题,又因为备份容灾不及时,导致部分数据恢复不了,而刚好这部分丢失的数据对于客户来说又是至关重要的,那么怎么办呢?盲 ...
- python - 代码练习 - 备份目录/文件(windos环境)
备份目录/文件 import zipfile import os,datetime class beifen(object): def __init__(self,files,new_files,co ...
随机推荐
- Sonar安装配置
https://www.sonarqube.org/downloads/ 下载sonar.当前版本为6.2 解压压缩包,进行配置: 修改sonarqube-6.2\conf\sonar.propert ...
- Robot Framework 安装步骤
1. 安装python 2.7.11, 并添加环境变量到PATH.在cmd验证python是否安装成功. 2. 解压pip-8.1.1.tar.gz,执行python setup.py insta ...
- linux下epoll实现机制
linux下epoll实现机制 原作者:陶辉 链接:http://blog.csdn.net/russell_tao/article/details/7160071 先简单回顾下如何使用C库封装的se ...
- 三种执行SQL语句的的JAVA代码
问题描述: 连接数据库,执行SQL语句是必不可少的,下面给出了三种执行不通SQL语句的方法. 1.简单的Statement执行SQL语句.有SQL注入,一般不使用. public static voi ...
- 学习MySQL之数据类型(四)
一. 整数类型: 整数类型 占用字节 最小值 最大值 TINYINT 1 有符号 -128 无符号0 有符号127 无符号255 SMALLINT 2 有符号-3 2768 无符号0 有符号3 2 ...
- ThinkPHP Where 条件中使用表达式
本文转自:这里 Where 条件表达式格式为: $map['字段名'] = array('表达式', '操作条件'); 其中 $map 是一个普通的数组变量,可以根据自己需求而命名.上述格式中的表达式 ...
- hdu2014青年歌手大赛
Problem Description 青年歌手大奖赛中,评委会给参赛选手打分.选手得分规则为去掉一个最高分和一个最低分,然后计算平均得分,请编程输出某选手的得分. Input 输入数据有多组,每组占 ...
- [Bash Shell] Shell学习笔记
1. Shell简介 Shell本身是一个用C语言编写的程序,它是用户使用Unix/Linux的桥梁,用户的大部分工作都是通过Shell完成的.Shell既是一种命令语言,又是一种程序设计语言.作为命 ...
- 执行mvn 报错 source-1.5 中不支持 diamond运算符
编译版本出现了问题 <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> < ...
- apache 配虚拟主机转发到tomcat
我用的是apache2.4.23, 连接tomcat使用自带的 proxy-ajp,需要开启相关模块 引用 http://www.server110.com/apache/201404/10273.h ...