开发者

How to open disks in windows and read data at low level?

I know in linux it is as simple as /dev/sda but in Windows how do you open a disk and start reading data at the low level?

In python I've tried:

f = open("K:", "r")

and I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: 'K:'

I get this error even as administrator开发者_运维问答.


From http://support.microsoft.com/kb/100027

To open a physical hard drive for direct disk access (raw I/O) in a Win32-based application, use a device name of the form

\\.\PhysicalDriveN

where N is 0, 1, 2, and so forth, representing each of the physical drives in the system.

To open a logical drive, direct access is of the form

\\.\X: 

where X: is a hard-drive partition letter, floppy disk drive, or CD-ROM drive.


Remember that all objects in windows and other operating systems are files. To open and read 16 bytes of data from drive E: use the code below:

# Open a Disk in binary format read only 16 bytes
file = "\\\\.\\E:"
with open(file,'rb') as f:
    print("Disk Open")
    data = f.read(16)
    # Convert the binary data to upper case hex ascii code
    hex_data = " ".join("{:02X}".format(c) for c in data)
    print(hex_data)


Both worked for me. To gain access to Partition C: or the whole drive, administrator privileges are needed. Here an example as replacement for open():

def open_physical_drive(
    number,
    mode="rb",
    buffering=-1,
    encoding=None,
    errors=None,
    newline=None,
    closefd=True,
    opener=None,
):
    """
    Opens a physical drive in read binary mode by default
    The numbering starts with 0
    """
    return open(
        fr"\\.\PhysicalDrive{number}",
        mode,
        buffering,
        encoding,
        errors,
        newline,
        closefd,
        opener,
    )


def open_windows_partition(
    letter,
    mode="rb",
    buffering=-1,
    encoding=None,
    errors=None,
    newline=None,
    closefd=True,
    opener=None,
):
    """
    Opens a partition of a windows drive letter in read binary mode by default
    """
    return open(
        fr"\\.\{letter}:", mode, buffering, encoding, errors, newline, closefd, opener
    )


# first 16 bytes from partition C:
# on Linux it's like /dev/sda1
with open_windows_partition("C") as drive_c:
    print(drive_c.read(16))


# first 16 bytes of first drive
# on Linux it's like /dev/sda
with open_physical_drive(0) as drive_0:
    print(drive_0.read(16))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜