当前位置 : 主页 > 编程语言 > java >

linux下使用python3发送邮件定时备份数据库脚本

来源:互联网 收集:自由互联 发布时间:2022-08-15
网站搭建完成后数据尤其重要,如下是整理的定时备份数据库并将数据库自动发送到我的另一个邮箱做备份,这样就相对安全多了 python3发送邮件脚本 vim / data / backup / script / send_email

网站搭建完成后数据尤其重要,如下是整理的定时备份数据库并将数据库自动发送到我的另一个邮箱做备份,这样就相对安全多了

python3发送邮件脚本

vim /data/backup/script/send_email.py
#!/usr/bin/python3
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
import os

if len(sys.argv) == 1:
print('请输入标题与附件')
sys.exit()

sender = 'h3blog***@163.com'
receiver = '46*****14@qq.com'
smtpserver = 'smtp.163.com'
username = 'h3blog***'
password = '123456***'
mail_title = sys.argv[1]

# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = sender
message['To'] = receiver
message['Subject'] = Header(mail_title, 'utf-8')

# 邮件正文内容
message.attach(MIMEText('备份服务器数据', 'plain', 'utf-8'))

for att in sys.argv[2:]:
# 构造附件1(附件为TXT格式的文本)
name = os.path.basename(att)
att1 = MIMEText(open(att, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="{}"'.format(name)
message.attach(att1)



smtpObj = smtplib.SMTP_SSL() # 注意:如果遇到发送失败的情况(提示远程主机拒接连接),这里要使用SMTP_SSL方法
smtpObj.connect(smtpserver)
smtpObj.login(username, password)
smtpObj.sendmail(sender, receiver, message.as_string())
print("邮件发送成功!!!")
smtpObj.quit()

该脚本可独立运行

./send_email.py 测试 /tmp/test.txt

shell脚本备份数据脚本

vim /data/backup/script/backupmysql.sh
#!/bin/bash
# Name:bakmysql.sh
#
backupdir=/data/backup/database
time=` date +%Y%m%d%H%M%S `
mysqldump -u root -p4232*** h3blog | gzip > $backupdir/h3blog_$time.sql.gz
#
find $backupdir -name "h3blog_*.sql.gz" -type f -mtime +7 -exec rm {} \; > /dev/null 2>&1

/data/backup/script/send_email.py bakup_mysql $backupdir/h3blog_$time.sql.gz

编辑cron定时任务

crontab -e
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command

0 1


网友评论