python 备份脚本

原来是ruby写的, 考虑不太全, 现在重写了一下。 按时间过滤相关东西

#!/usr/bin/env python

import os
import re
import time
import tarfile
import string

bak_ser = "[email protected]"
tar_dir = "/tmp/auto_tar_bak"
ext_user = "/eda/bin/auto_bak.conf"
config = {"deep":8, "exclude":"Code|INCA.libs", "filetype":"bmp|png|pdf|vsd|rar|log|dat|bak|sdb"}
current_time = int(time.time())

def check_bak(bak_dir):
    tmp_list = []
    for filepath,pathlist,filelist in os.walk(bak_dir): 
        #filepath  fullpath
        #pathlist  fullpath child dir
        #filelist  child dir file
        if filepath.count("/") >= config["deep"] or ".svn" in pathlist:
            continue
        for filename in filelist:
            if os.path.islink("%s/%s" % (filepath, filename)) or "/." in filepath or filename.startswith(".") or re.findall(config["filetype"], filename.split(".")[-1], re.I) or re.findall(config["exclude"], filepath):
                continue
            elif 120 <= os.path.getsize("%s/%s" % (filepath, filename)) <= 10485760 and current_time - os.stat("%s/%s" % (filepath, filename))[-2] < 172800 and istext("%s/%s" % (filepath, filename)):
                tmp_list.append("%s/%s" % (filepath, filename))
    return tmp_list           

def istext(filename):
    s=open(filename).read(512)
    text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
    _null_trans = string.maketrans("", "")
    if not s:
        # Empty files are considered text
        return True
    if "\0" in s:
        # Files with null bytes are likely binary
        return False
    # Get the non-text characters (maps a character to itself then
    # use the ‘remove‘ option to get rid of the text characters.)
    t = s.translate(_null_trans, text_characters)
    # If more than 30% non-text characters, then
    # this is considered a binary file
    if float(len(t))/float(len(s)) > 0.30:
        return False
    return True

def create_tarfile(tar_name, filename, tar_list):
    if not os.path.isdir(tar_name):
        os.makedirs(tar_name)
    bak_tar = tarfile.open(tar_name + filename, "w:bz2")
    for i in tar_list:
        bak_tar.add(i)
    bak_tar.close()

def get_bak_dir():
    tmp = []
    with open("/etc/auto.nfs") as f:
        for i in f:
            if os.uname()[1] in i and not i.startswith("#"):
                tmp.append(i.split("/")[-1].rstrip())
    return tmp
                
if __name__ == "__main__":
    ext_list = []
    with open(ext_user) as f:
        for i in f.read():
            ext_list = i.split()
    for dirname in get_bak_dir():
        if dirname in ext_list:
            continue
        file_list = check_bak("/local_home/" + dirname)
        if file_list:
            filename = time.strftime("/%F.tar.bz2", time.localtime())
            create_tarfile(tar_dir + "/" + dirname, filename, file_list)
            os.system("rsync -az --remove-source-files %s/%s%s %s:/bak/auto_bak/%s/" %(tar_dir, dirname, filename, bak_ser, dirname))
时间: 2024-08-08 13:46:17

python 备份脚本的相关文章

Python备份脚本(Win10+Python2.7+PyCharm)

说一下程序来源,是从<Python简明教程>上面看到的程序,试了一下之后,居!然!不!行!!! Google了老半天,也看了好多个博客,也未能解决. 除了一些基本语法问题.字符串中队'\'的处理的问题等之外,此处假设程序本身没什么问题了,主要是zip_command这个指令出现的问题.其中最常见的问题就是zip不是什么内部指令的那个了,如下图: 先说一下我的解决方法,是从万能的知乎上找到的方案,话不多说,直奔重点. 下了一个7-zip的软件,安装一下,要记住你的安装路径! 先贴代码吧,如下所示

python备份脚本

本文参考简明python后修改 #!/usr/bin/python import time import os # 1. The files and directories to be backed up are specified in a list. source = ['/root', '/tmp'] # If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that #

[简明python教程]学习笔记之编写简单备份脚本

[[email protected] 0503]# cat backup_ver3.py #!/usr/bin/python #filename:backup_ver3.py import os import time #source source=['/root/a.sh','/root/b.sh','/root/c.sh'] #source='/root/c.sh' #backup dir target_dir='/tmp/' today=target_dir+time.strftime('

利用Python编写linux自动备份脚本

题目: 周末的时候帮朋友写了一个备份需求的脚本,现在整理一下,分享出来使用Python语言的Fabric模块,这里就不扫盲了,运维必用的Python模块: 大概要求: 公司需求,每天凌晨2点备份数据(数据量不大,每天全备),拷贝至备份服务器,通过md5对比备份文件(本机备份文件和备份服务器文件对比),并将备份情况通知运维组同学. 备份思路: (1.每天凌晨2点在服务器本地使用tar打包备份文件: (2.备份成功以后,推送至备份服务器: (3.校验本地备份文件和备份服务器文件的完整性和一致性: (

python备份mysql脚本

今天简单的写了个python的mysql备份脚本,其实也不是很难呀.比shell简洁了很多! 开整: 注释都用英文写了,有些英语基础的朋友应该都可以看得懂了! #!/usr/bin/env python #backup the gtshop #author:ley #encoding=utf8 #date:2015-06 import os,sys,datetime,time from stat import * #mysqlbackup user User = 'root' #mysqlbac

python备份数据库

向python进军...... 运行所需环境:python,MySQLdb 贴下自己写的关于sql备份的python脚本: #!/usr/bin/env pythonimport MySQLdbimport osimport timedataList=[]remoteAddr='xxxx'user='root'password='xxxx'dbConnect = MySQLdb.connect(%s,%s,%s)%(remoteAddr,user,password)cursor=dbConnec

MySQL备份脚本V2(添加日志功能及备份后检查)

备份脚本 #!/usr/bin/env python #_*_coding:utf-8_*_ """ @File: backup_db.py @Author: OldTan @Email: [email protected] @Last Modified: 20180408 """ import os import datetime from threading import Thread from logs import log HOST = 

Python备份H3C交换机配置并上传到tftp

实验环境: centos7 python3 pip3 install netmiko 1. python脚本 import time from netmiko import ConnectHandler now = time.strftime("%Y%m%d", time.localtime(time.time())) log_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ip_list =

WEB页面,WEB环境版本,数据库,整站备份脚本

#!/bin/bash # #WEB页面,WEB环境版本,数据库,整站备份脚本 #当发生某个原因导致整个服务器无法恢复时,利用上面备份的相关数据即可重做一台一样的服务器 date_a=`date +%Y%m%d-%H%M%S` mkdir -p /web_bak/${date_a}/conf &> /dev/null mkdir -p /web_bak/${date_a}/web &> /dev/null mkdir -p /web_bak/${date_a}/mysql &a