Marcus Stein
Marcus Stein

Reputation: 63

How do I securely wipe a file / directory in Python?

Is there any module which provides somehow basic "secure" deletion, sth. like the Linux utility "wipe", e.g.

import securitystuff

securitystuff.wipe( filename )

I need to protect company source code which should not be easily retrievable anymore.

P.S. Yes I know "wipe" is not perfect, e.g. on journalling filesystem. But the security demand is not tooo high.

Upvotes: 6

Views: 4520

Answers (2)

CertifcateJunky
CertifcateJunky

Reputation: 171

def secure_delete(path, random_fill=True, null_fill=True, passes=3):
    """
    securely delete a file by passing it through both random and null filling
    """
    files = os.listdir(path)
    for i, f in enumerate(files):
        files[i] = "{}/{}".format(path, f)
    for item in files:
        with open(item, "wr") as data:
            length = data.tell()
            if random_fill:
                for _ in xrange(passes):
                    data.seek(0)
                    data.write(os.urandom(length))
            if null_fill:
                for _ in xrange(passes):
                    data.seek(0)
                    data.write("\x00" * length)
        os.remove(item)

Note this will wipe the file to the point that it will be virtually impossible to recover with a standard system, but this is not going to stop someone who really wants your data from recovering the file. You might be able to implement it with the above answer to make it more secure.

Upvotes: -1

Anurag Uniyal
Anurag Uniyal

Reputation: 88847

There is no such function in standard library and a naive implementation which overwrites each byte of file with a random byte is not too difficult to do e.g.

 f = open(path, "wb")
 f.write("*"*os.path.getsize(path))
 f.close()
 os.unlink(path)

But as suggested in thread http://mail.python.org/pipermail/python-list/2004-September/899488.html this doesn't guarantee wiping due to many reasons, e.g. disk cache, remapping of disk sectors etc etc

So instead of implementing your own wipe easiest would be to call linux wipe from python.

Alternate option is to use srm

Upvotes: 5

Related Questions