对目录数据进行归档及删除实例:

vi a1.py

#!/usr/bin/python

import os import datetime import shutil import sys

reload(sys) sys.setdefaultencoding('utf-8')

dir="/historybackup2/PRD" dst="/historybackup2/Daybackup/PRD"

yesterday = datetime.date.today() - datetime.timedelta(days=1) yesterday2 = datetime.datetime.now() - datetime.timedelta(days=15) yesterday3 = datetime.datetime.now() - datetime.timedelta(days=45)

os.remove("/historybackup2/shell/logs/PRD.txt") os.mknod("/historybackup2/shell/logs/PRD.txt") os.remove("/historybackup2/shell/logs/PRD2.txt") os.mknod("/historybackup2/shell/logs/PRD2.txt") os.remove("/historybackup2/shell/logs/PRD_2.txt") os.mknod("/historybackup2/shell/logs/PRD_2.txt") os.remove("/historybackup2/shell/logs/PRD2_2.txt") os.mknod("/historybackup2/shell/logs/PRD2_2.txt")

os.chdir(dst) os.mkdir(str(yesterday))

os.chdir(dir)

for root,dirs,files in os.walk("."): for f in files: mtime = datetime.date.fromtimestamp(os.path.getmtime(os.path.join(root,f))) if mtime == yesterday: z = open('/historybackup2/shell/logs/PRD2.txt','a') z.write(str(mtime)+"\n") z.close()

                 p = open('/historybackup2/shell/logs/PRD.txt','a')
                 p.write(os.path.join(root,f)+"\n")
                 p.close()

size = 0 c = open('/historybackup2/shell/logs/PRDBACKUP.txt','r') for i in c.readlines(): b = os.path.getsize(i.strip())
size += int(b) si = (format((float(size) / 1024 / 1024 / 1024),'.1f')) e = open('/historybackup2/shell/logs/PRD3.txt','w') e.write(str(si)+'G') e.close()

x = open('/historybackup2/shell/logs/PRD.txt','r') for n in x.readlines(): m = os.path.dirname(n.strip()).strip('./') s = os.path.join(dst,str(yesterday)) if not os.path.exists(os.path.join(s,m)): os.makedirs(os.path.join(s,m)) shutil.copy2(n.strip(),os.path.join(s,n.strip()))

for f2 in os.listdir(dir): mtime = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(dir,f2))) if mtime < yesterday2: z2 = open('/historybackup2/shell/logs/PRD2_2.txt','a') z2.write(str(mtime)+"\n") z2.close()

                 p2 = open('/historybackup2/shell/logs/PRD_2.txt','a')
                 p2.write(f2+"\n")
                 p2.close()

x2 = open('/historybackup2/shell/logs/PRD_2.txt','r') for n2 in x2.readlines(): if os.path.isfile(n2.strip()): os.remove(n2.strip()) if os.path.isdir(n2.strip()): shutil.rmtree(n2.strip())

os.chdir(dst)

for f3 in os.listdir(dst): if os.path.isdir(f3): mtime3 = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(dst,f3))) if mtime3 < yesterday3 and f3 != "2018-01-01" and f3 != "2018-02-01" and f3 != "2018-03-01" and f3 != "2018-04-01" and f3 != "2018-05-01" and f3 != "2018-06-01" and f3 != "2018-07-01" and f3 != "2018-08-01" and f3 != "2018-09-01" and f3 != "2018-10-01" and f3 != "2018-11-01" and f3 != "2018-12-01": shutil.rmtree(f3)

os.system('/usr/bin/mail -s "host1(10.0.0.2) aa archive yesterday Size at date +%Y-%m-%d" zhi.yang@ming.com < /historybackup2/shell/logs/PRD3.txt')

:wq

python a1.py