sqlmap/lib/utils/purge.py

84 lines
2.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python
"""
2016-01-06 02:06:12 +03:00
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
import random
import shutil
import stat
import string
2015-11-23 11:24:30 +03:00
from lib.core.common import getSafeExString
from lib.core.data import logger
def purge(directory):
"""
Safely removes content from a given directory
"""
2012-04-23 18:33:36 +04:00
if not os.path.isdir(directory):
2012-04-23 18:43:59 +04:00
warnMsg = "skipping purging of directory '%s' as it does not exist" % directory
logger.warn(warnMsg)
2012-04-23 18:33:36 +04:00
return
2013-04-22 13:38:47 +04:00
infoMsg = "purging content of directory '%s'..." % directory
2012-04-23 18:33:36 +04:00
logger.info(infoMsg)
filepaths = []
dirpaths = []
for rootpath, directories, filenames in os.walk(directory):
dirpaths.extend([os.path.abspath(os.path.join(rootpath, _)) for _ in directories])
filepaths.extend([os.path.abspath(os.path.join(rootpath, _)) for _ in filenames])
2013-04-22 13:38:47 +04:00
logger.debug("changing file attributes")
for filepath in filepaths:
try:
os.chmod(filepath, stat.S_IREAD | stat.S_IWRITE)
except:
pass
2013-04-22 13:38:47 +04:00
logger.debug("writing random data to files")
for filepath in filepaths:
try:
filesize = os.path.getsize(filepath)
2014-04-07 22:06:03 +04:00
with open(filepath, "w+b") as f:
f.write("".join(chr(random.randint(0, 255)) for _ in xrange(filesize)))
except:
pass
2013-04-22 13:38:47 +04:00
logger.debug("truncating files")
for filepath in filepaths:
try:
with open(filepath, 'w') as f:
pass
except:
pass
2013-04-22 13:38:47 +04:00
logger.debug("renaming filenames to random values")
for filepath in filepaths:
try:
os.rename(filepath, os.path.join(os.path.dirname(filepath), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
except:
pass
2013-01-10 16:18:44 +04:00
dirpaths.sort(cmp=lambda x, y: y.count(os.path.sep) - x.count(os.path.sep))
2013-04-22 13:38:47 +04:00
logger.debug("renaming directory names to random values")
for dirpath in dirpaths:
try:
os.rename(dirpath, os.path.join(os.path.dirname(dirpath), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
except:
pass
2013-04-22 13:38:47 +04:00
logger.debug("deleting the whole directory tree")
os.chdir(os.path.join(directory, ".."))
2013-11-24 18:01:26 +04:00
try:
shutil.rmtree(directory)
except OSError, ex:
2015-11-23 11:24:30 +03:00
logger.error("problem occurred while removing directory '%s' ('%s')" % (directory, getSafeExString(ex)))