Block-Device

在塊設備上查找/替換?

  • January 21, 2015

假設我有一個未安裝的塊設備/dev/sda,我想用 替換所有MyPassWord實例XXXXXXXXXX。(希望我的目標很明顯。)

最簡單的方法是什麼?

您可以執行以下操作:

#! /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並確保在完成後重新安裝設備,因為文件內容的系統緩衝區不會收到更改通知。

引用自:https://unix.stackexchange.com/questions/180303