Let's say I have an unmounted block device /dev/sda, and I want to replace all instances of MyPassWord with XXXXXXXXXX. (Hopefully my goal is obvious.)
What's the easiest way to do this?
Let's say I have an unmounted block device /dev/sda, and I want to replace all instances of MyPassWord with XXXXXXXXXX. (Hopefully my goal is obvious.)
What's the easiest way to do this?
You can do something like:
#! /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
substituting the appropriate device name at the top.
You have to run the script as root and make sure you re-mount the device when finished as the system buffers of file contents are not notified of the changes.
MyPassWord if it falls any 1Mb boundary. +1 though
MyPassWord is in a file and the blocks that hold the date of that file are not next to each other in the file, then this won't work. In that case you would need to scan each and every file through the filesystem, and do the same for deleted file that might be recovered (e.g. with extundelete)