securely overwrite files with Python

Bart Nessux bart_nessux at hotmail.com
Fri Mar 5 21:31:43 EST 2004


Skip Montanaro wrote:

> 
>     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

Thanks Skip! I'll give this a go.



More information about the Python-list mailing list