Write zeros to file blocks

最后都变了- 提交于 2021-01-27 14:08:02

问题


I'm attempting to identify the blocks that are tied to a specific file and write zeros to them. I've found several methods that do this to the free space on a disk, but so far I haven't found any slid suggestions for doing the following:

  • identify the blocks for a file
  • Write zeros to those blocks.

The purpose of this is for a virtualized system. This system has the ability to dedupe blocks that are identified as being the same. This is used to reduce space used by the guest OSes on the drive.

Currently this is being done using dd to write zeros to the free space on the drive. However this has the side effect on VMWare systems to cause the guest OS drive to use the entire disk space it has been allocated as from that point on the system things all the bytes have been written to.


回答1:


Writing code that can safely modify even an unmounted filesystem will require significant effort. It is to be avoided unless there is no other option.

You basically have two choices to make modifying the filesystem easy:

  • Run python in the virtual environment.
  • Mount the virtualized filesystem on the host. Most UNIX-like systems can do that, e.g. with the help of FUSE (which support a lot of filesystem types) and loop devices.

This way you can use the (guest or host) OS's filesystem code instead of having to roll your own. :-) If you can use one of those options, the code fragment listed below will fill a file with zeroes:

import os

def overwrite(f):
    """Overwrite a file with zeroes.

    Arguments:
    f -- name of the file
    """
    stat = os.stat(f)
    with open(f, 'r+') as of:
        of.write('\0' * stat.st_size)
        of.flush()


来源:https://stackoverflow.com/questions/12768026/write-zeros-to-file-blocks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!