Skip to content

Instantly share code, notes, and snippets.

@mitchellrj
Last active June 5, 2018 16:36
Show Gist options
  • Save mitchellrj/c6e21f6d885d7aea7afaa69d69f78950 to your computer and use it in GitHub Desktop.
Save mitchellrj/c6e21f6d885d7aea7afaa69d69f78950 to your computer and use it in GitHub Desktop.
Cheap and cheerful image recovery from a corrupted SD card that keeps unmounting itself
# usage:
# sudo python reader.py /dev/disk2s2 path-to-my-image.img
#
# keep re-inserting the card and hitting enter as instructed
import os.path
import sys
infile = sys.argv[1]
outfile = sys.argv[2]
with open(outfile, 'wb') as ofh:
blocks_read = 0
while True:
try:
ifh = open(infile, 'rb')
except (IOError, OSError):
raw_input('Failed to open. Reinsert and press enter.')
continue
try:
ifh.seek(blocks_read * 512)
except IOError:
raw_input('Failed to seek. Reinsert and press enter.')
continue
try:
d = ifh.read(512)
except IOError:
print('block {:06d}: skipped'.format(blocks_read))
ofh.write('\00' * 512)
# close the file to free the handle - if left open it holds the volume mounted
# even if it has become unreadable. closing the file at this point allows it to
# unmount if it thinks it needs to.
ifh.close()
try:
os.stat(infile)
except (IOError, OSError):
raw_input('Failed to read. Reinsert and press enter.')
else:
print('block {:06d}: read'.format(blocks_read))
ofh.write(d)
ofh.write('\00' * (512 - len(d)))
blocks_read += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment