securely overwrite files with Python

Skip Montanaro skip at pobox.com
Fri Mar 5 16:21:19 EST 2004


    Bart> Is there a shred module in Python? You know, the kind that
    Bart> overwrites files that one doesn't want others to see? 

I've never used shred before, but here's an essentially untested stab at the
problem:

    #!/usr/bin/env python

    import os
    import random
    import sys
    import md5

    def shred(f, npasses=5):
        sz = os.path.getsize(f)
        for n in range(npasses):
            dig = md5.new(file(f).read()).hexdigest()
            print >> sys.stderr, "pass:", n+1,
            print >> sys.stderr, "digest:", dig
            chars = [chr(i) for i in range(128)]
            random.shuffle(chars)
            chars = "".join(chars)
            bytesleft = sz
            fp = file(f, "wb")
            while bytesleft:
                nbytes = min(bytesleft, 128)
                fp.write(chars[:nbytes])
                bytesleft -= nbytes
            fp.close()
        dig = md5.new(file(f).read()).hexdigest()
        print >> sys.stderr, "last digest:", dig
        os.unlink(f)

    if __name__ == "__main__":
        tmpf = "dummyf"
        file(tmpf, "wb").write(file("/etc/hosts").read()*5)
        shred(tmpf)

Note that it does no error checking, nor does it have any force write arg.

Skip




More information about the Python-list mailing list