如何使用Python在Windows中获取原始磁盘或块设备的大小

4
我如何在Windows中从块设备或原始磁盘上获取大小,如果我只知道设备名称是"\.\PhysicalDrive0",它上面没有文件系统或卷标?
我的尝试如下:
fd = os.open(r"\.\PhysicalDrive0", os.O_RDONLY) os.lseek(fd, 0, os.SEEK_END)
在Linux上它很好用,但在Windows上总是返回"OSError: [Errno 22] Invalid argument"。
我也尝试了ctypes.windll.kernel32.GetDiskFreeSpaceExW(),但它似乎只适用于带有文件系统和分配的卷标的磁盘。
对于原始磁盘或块设备,应该如何正确操作呢?
提前感谢。

可能会回答你的问题。请访问此链接:https://dev59.com/BGw05IYBdhLWcg3wnjEk - ojs
谢谢,这是很棒的信息。现在我可以写入它了,但是当我使用.seek(0,2)或.seek(0,os.SEEK_END)来获取大小时,它什么也没有返回,似乎不知道设备的末尾在哪里。 - kli
现在你似乎正在使用与文件对象相关联的seek方法(而不是lseek),你是否已经将os.open返回的文件描述符更改为文件对象?你可以使用os.fdopen来实现这一点。 - ojs
是的,就像fo=os.fdopen(os.open("\\.\PhysicalDrive3", os.O_RDONLY|os.O_BINARY), "rb+"),以及fo.seek(0,2)不起作用。 - kli
2个回答

2
使用 wmi 模块。
import wmi
c = wmi.WMI()
[drive] = c.Win32_DiskDrive(Index=0)
print("The disk has %s bytes" % drive.size)
print("Or %s GB" % int(int(drive.size) / 1024**3))

磁盘容量为320070320640字节
或298 GB

此代码查询WMI接口中的Win32_DiskDrive对象,其中Index等于0(因此只有一个结果,该结果为PHYSICALDRIVE0)。 drive对象具有名为size的属性,该属性是一个字符串,包含驱动器的字节大小。


0
我有一个解决方案,但它不太好看。使用diskpart。不幸的是,它不能给你一个精确的字节大小,如果需要的话,但它可以给你一个可读的字符串。
import tempfile
import subprocess
import re
import os

def query_diskpart(command):
    """Run command script for diskpart.

    Args:
        command(str): String of all commands to run against diskpart
    Returns:
        String of all diskpart standard output
    Size Effects:
        Creates a temporary file(and then deletes it)
        Creates a subprocess to run diskpart
    """
    with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_handle:
        temp_handle.write(command)
    # The temporary file needs to be closed before opening with diskpart
    diskpart_handle = subprocess.Popen(["diskpart", '/s', temp_handle.name], stdout=subprocess.PIPE)
    output, _ = diskpart_handle.communicate()

    os.remove(temp_handle.name)
    return output

def match_drive_size(diskpart_output, disk_num):
    """Get drive size from diskpart output.

    Args:
        diskpart_output(str): String of diskpart standard output
        disk_num(int): Number of PhysicalDrive to match against
    Returns:
        Human readable size of drive.
    Raises:
        ValueError if drive doesn't exist.
        """

    # Break up gigantic output string
    output_lines = diskpart_output.decode().split(os.linesep)
    # Apply regular expression to every line, but it should only match one
    matches = [re.match(".*Disk %s\s*(.*)" % disk_num, line) for line in output_lines]
    size = None
    for match in matches:
        if match:
            # Get first subgroup (parens above)
            size_line = match.group(1)
            # Split by whitespace
            size_list = re.split("\s*", size_line)
            # Merge numerical value + units
            # ['256', 'GB'] becomes 256GB
            size = ''.join(size_list[1:3])
            break
    else:
        raise ValueError("PHYSICALDRIVE%s does not exist", disk_num)
    return size

def get_drive_size(disk_num):
    """Get Windows Drive size.

    Args:
        disk_num(int): The Physical Drive Number
            e.g. for PHYSICALDRIVE0 put 0
    Returns:
        Human readable string of the drive size
    """
    output = query_diskpart("list disk\n")
    drive_size = match_drive_size(output, disk_num)
    return drive_size

if __name__ == "__main__":
    print(get_drive_size(0))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接