在块设备上查找/替换?

在块设备上查找/替换?

假设我有一个未安装的块设备/dev/sda,我想用 替换 的所有MyPassWord实例XXXXXXXXXX。 (希望我的目标是显而易见的。)

做到这一点最简单的方法是什么?

答案1

你可以这样做:

#! /usr/bin/env python

device = '/dev/sdi'
old_pattern = "MyPassWord"
new_pattern = "XXXXXXXXXX"

assert len (old_pattern) == len(new_pattern)

BS = 1024 ** 2  # 1 Mb buffer
# read a few bytes more to account for occurences of the pattern on the edge
READSIZE = BS + len(old_pattern)

offset = 0
with open(device, 'r+b') as fp:
    assert isinstance(fp, file)
    while True:
        try:
            fp.seek(offset)
        except IOError:
            #print 'offset', offset
            #raise
            break
        buf = fp.read(READSIZE)
        occurences = buf.count(old_pattern)
        if occurences:
            print offset, occurences
            fp.seek(offset)
            fp.write(buf.replace(old_pattern, new_pattern))
            fp.flush()
        offset += BS

在顶部替换适当的设备名称。

您必须运行脚本root并确保完成后重新挂载设备,因为文件内容的系统缓冲区不会收到更改通知。

相关内容