常用python脚本
     分类:Python     有: 0 条评论

常用python脚本

     分类:Python     有: 0 条评论

网站自动备份脚本

这个是用python实现的,导出数据库后将网站目录和数据库打包并压缩为 xxx.tar.gz 文件,最后通过邮件发送备份包到指定邮箱;支持Windows,Linux;如果只是Linux也可以用shell使用tar、mysqldump、rsync等命令完成这个功能。

安装开发版python

apt-get install python-dev                 # Debian系
apt-get install libmysqlclient-dev         # Debian系  

yum install libmysqlclient-devel           # RedHat系  
yum install python-devel                   # RedHat系

安装MySQL-python
打开网站下载合适的版本:https://pypi.python.org/pypi/MySQL-python

python setup.py install

安装ConfigParser
打开网站下载合适的版本:https://pypi.python.org/pypi/configparser

python setup.py install

python脚本
原项目地址:https://github.com/Weic96/Site-Backup-Python

# -*- coding: utf-8 -*-
from email import encoders
from email.header import Header
from email.utils import parseaddr, formataddr
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from time import strftime,gmtime
import smtplib, MySQLdb, time, os, tarfile, ConfigParser

config=ConfigParser.ConfigParser()
config.read("site-backup.cfg")

# 获取时间
serverTime = str(time.strftime("%Y-%m-%d"))
backTime = float(config.get("time", "backTime"))
# 邮件变量
from_addr = config.get("mail", "from_addr")
password = config.get("mail", "password")
smtp_server = config.get("mail", "smtp_server")
to_addr = config.get("mail", "to_addr")
mail_sender = config.get("mail", "mail_sender")
mail_recipient =  config.get("mail", "mail_recipient")
mail_title = config.get("mail", "mail_title")
# Mysql变量
mysql_host = config.get("mysql", "mysql_host")
mysql_user = config.get("mysql", "mysql_user")
mysql_password = config.get("mysql", "mysql_password")
mysql_database = config.get("mysql", "mysql_database")

# 网站文件变量
siteName = config.get("flies", "siteName")
dirName = siteName + "-" + serverTime
dirPath = config.get("flies", "dirPath")
siteBack_name = 'dirName.tar.gz'

# SQL和压缩包变量
backMysql_name = siteName + "-" + serverTime + '.sql'
sendSitePack = dirName + ".tar.gz"


# 导出数据库函数
def outMysql():
    mysql_cmd = "mysqldump -u " + mysql_user + " -p" + mysql_password + " " + mysql_database + " > " + dirPath + backMysql_name
    os.system(mysql_cmd)

# 打包网站文件函数
def siteFile():
    t = tarfile.open(dirName + ".tar.gz", "w:gz")
    for root, dir, files in os.walk(dirPath):
        for file in files:
            fullpath = os.path.join(root, file)
            t.add(fullpath)
    t.close()

# 发送邮件(备份包)函数
def sendMail():
    message = MIMEMultipart()
    message.attach(MIMEText('备份于' + serverTime, 'plain', 'utf-8'))
    att = MIMEText(open(sendSitePack, 'rb').read(), 'base64', 'gb2312')
    att["Content-Type"] = 'application/octet-stream'
    att["Content-Disposition"] = "attachment; filename=" + sendSitePack
    message.attach(att)
    message['From'] = mail_sender
    message['To'] = mail_recipient
    message['Subject'] = mail_title + serverTime

    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], message.as_string())
    server.quit()


# 整个任务函数
def backSite():
    outMysql()
    if os.path.exists(dirPath + backMysql_name):
        siteFile()

    if os.path.exists(sendSitePack):
        sendMail()

    os.remove(dirPath + backMysql_name)
    os.remove(sendSitePack)

# 循环执行备份任务
while True:
    backSite()
    time.sleep(backTime)

配置文件

# 如果有看不懂的可以前往作者博客留言 https://weic96.cn/python-site-backup

[mail]
# 发件人邮箱
from_addr = xxx@qq.com
# 发件人邮箱密码或者授权码
password = xxxxxxxxxxxxx
# smtp服务器
smtp_server = smtp.qq.com
# 收件人邮箱
to_addr = xxx@qq.com
# 发件人
mail_sender =
# 收件人
mail_recipient =
# 邮件标题
mail_title =

[flies]
# 网站名
siteName =
# 需要备份的网站目录路径,结尾必须加上\(WINDOWS)或/(Linux)
dirPath =

[mysql]
# Mysql服务器
mysql_host = loaclhost
# Mysql用户名
mysql_user =
# Mysql密码
mysql_password =
# 需要备份Mysql数据库
mysql_database =

[time]
# 备份时间间隔,单位为秒,建议12小时,即43200秒
backTime = 43200

运行脚本

# Linux:执行后在后台运行,需要结束就kill掉
nohup python site-backup.py > /dev/null &

# Windows:执行后在前台,关闭窗口就会结束脚本
python site-backup.py

对比时区时间

主要是线上环境用到了WIN服务器,对时间有要求,配合zabbix弄了个检测时间时区变化的脚本。

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# 导入库,pytz是一个时区转换库
import time
import ntplib
import pytz
import datetime

# 设置要比对的时区并获取时区时间
tz = pytz.timezone('Asia/Shanghai')
timezone = datetime.datetime.now(tz).strftime('%Y%m%d%H%M%S')

def get_time():
    ntp_client = ntplib.NTPClient()
    response = ntp_client.request('s2g.time.edu.cn')
    wtime = time.strftime('%Y%m%d%H%M%S', time.localtime(response.tx_time))
    return wtime

# abs可以获取绝对值
if __name__ == '__main__':
    networktime = get_time()
    local_time = time.strftime('%Y%m%d%H%M%S')
    difference_a = abs(int(networktime) - int(local_time))
    difference_b = abs(int(timezone) - int(local_time))


# 先判断本地时间与NTP的时间差值,小于180(说明与时区时间基本一致),再判断时区;大于180,则需要同步时间。
# 判断时区,差值大于1200(接近20分钟,没有转成十进制时间了)则不是所期望的时区,需要修改时区。
# 配合zabbix报警,0是正常,1是时区错误,2是时间错误。
if difference_a <= 180:
    if difference_b >= 1200:
        print 1
    else:
        print 0
else:
    print 2
(●゚ω゚●)