Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sqlmapproject
GitHub Repository: sqlmapproject/sqlmap
Path: blob/master/lib/utils/purge.py
2989 views
1
#!/usr/bin/env python
2
3
"""
4
Copyright (c) 2006-2025 sqlmap developers (https://sqlmap.org)
5
See the file 'LICENSE' for copying permission
6
"""
7
8
import functools
9
import os
10
import random
11
import shutil
12
import stat
13
import string
14
15
from lib.core.common import getSafeExString
16
from lib.core.common import openFile
17
from lib.core.compat import xrange
18
from lib.core.convert import getUnicode
19
from lib.core.data import logger
20
from thirdparty.six import unichr as _unichr
21
22
def purge(directory):
23
"""
24
Safely removes content from a given directory
25
"""
26
27
if not os.path.isdir(directory):
28
warnMsg = "skipping purging of directory '%s' as it does not exist" % directory
29
logger.warning(warnMsg)
30
return
31
32
infoMsg = "purging content of directory '%s'..." % directory
33
logger.info(infoMsg)
34
35
filepaths = []
36
dirpaths = []
37
38
for rootpath, directories, filenames in os.walk(directory):
39
dirpaths.extend(os.path.abspath(os.path.join(rootpath, _)) for _ in directories)
40
filepaths.extend(os.path.abspath(os.path.join(rootpath, _)) for _ in filenames)
41
42
logger.debug("changing file attributes")
43
for filepath in filepaths:
44
try:
45
os.chmod(filepath, stat.S_IREAD | stat.S_IWRITE)
46
except:
47
pass
48
49
logger.debug("writing random data to files")
50
for filepath in filepaths:
51
try:
52
filesize = os.path.getsize(filepath)
53
with openFile(filepath, "w+b") as f:
54
f.write("".join(_unichr(random.randint(0, 255)) for _ in xrange(filesize)))
55
except:
56
pass
57
58
logger.debug("truncating files")
59
for filepath in filepaths:
60
try:
61
with open(filepath, 'w') as f:
62
pass
63
except:
64
pass
65
66
logger.debug("renaming filenames to random values")
67
for filepath in filepaths:
68
try:
69
os.rename(filepath, os.path.join(os.path.dirname(filepath), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
70
except:
71
pass
72
73
dirpaths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep)))
74
75
logger.debug("renaming directory names to random values")
76
for dirpath in dirpaths:
77
try:
78
os.rename(dirpath, os.path.join(os.path.dirname(dirpath), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
79
except:
80
pass
81
82
logger.debug("deleting the whole directory tree")
83
try:
84
shutil.rmtree(directory)
85
except OSError as ex:
86
logger.error("problem occurred while removing directory '%s' ('%s')" % (getUnicode(directory), getSafeExString(ex)))
87
88