usr bin env python Скрипт удаления файлов 2007-2017 by Paul Dmitryev u

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
#!/usr/bin/env python
# Скрипт удаления файлов
# (C) 2007-2017 by Paul Dmitryev under GPL v3 or above
# Используйте с осторожностью!
from ConfigParser import ConfigParser
from os import walk, remove
from os.path import join, getsize
from re import compile, IGNORECASE
from shutil import move as move_file
def log_it(string):
f = open("terminator.log", "a")
f.write("%s\n" % string)
f.close()
def file_match(fn, re, size, mins, maxs, f_root):
result = True
if re!=None:
result = result & (re.search(fn)!=None)
if size!=-1:
if mins!=0:
result = result & (size<mins)
if maxs!=0:
result = result & (size>maxs)
return result
def take_file_actn(filen, filep, actions, size):
for act in actions.split(","):
full_n = join(filep, filen)
if act == "delete":
remove(full_n)
elif act == "log":
log_it("Found file: %s (%.2f Kb)" % (full_n, size / 1024.0))
elif act.find("moveto")==0:
[dummy, dest] = act.split(":")
move_file(full_n, join(dest, filen))
else:
log_it("Incorrect action: %s" % act)
def scan_dir(root_dir, rules):
total_size = 0
total_count = 0
for root, dirs, files in walk(root_dir):
for file in files:
for rule in rules:
(re, min_size, max_size, actn) = rule
try:
size = getsize(join(root, file))
except:
log_it("Error getting size for file %s" % full_name)
size = -1
if file_match(file, re, size, min_size, max_size, root):
take_file_actn(file, root, actn, size)
total_size += size
total_count += 1
return (total_size, total_count)
def dict_from_config_file(raw=False, vars=None):
"""Convert an INI file to a dictionary"""
config = ConfigParser()
config.read("./terminator.dat")
result = {}
for section in config.sections():
if section not in result:
result[section] = {}
for option in config.options(section):
value = config.get(section, option, raw, vars)
result[section][option] = value
return result
def main():
reslt = []
optns = dict_from_config_file()
root_dir = optns["Main"]["scandirs"]
rules = optns["Main"]["rules"].split(",")
for rule in rules:
if optns[rule].has_key("minsize"): #Python 2.5 rockz! :-(
sz_min = int(optns[rule]["minsize"]) or 0
else:
sz_min = 0
if optns[rule].has_key("maxsize"):
sz_max = int(optns[rule]["maxsize"]) or 0
else:
sz_max = 0
try:
reg = compile(optns[rule]["re"], IGNORECASE)
except:
reg = None
reslt.append((reg, sz_min, sz_max, optns[rule]["action"]))
(ts, tc) = scan_dir(root_dir, reslt)
log_it("Totally found: %d files, %.2f Kb " % (tc, ts / 1024.0))
if __name__=="__main__":
main()