gpt4 book ai didi

python - 在 Windows 上将原始数据写入物理磁盘(闪存驱动器)失败并显示 "Bad file descriptor"- Python

转载 作者:可可西里 更新时间:2023-11-01 14:14:23 31 4
gpt4 key购买 nike

我正在尝试在 Windows 上将 USB 闪存驱动器作为物理驱动器执行直接数据读取和写入(如果重要,则为 10 个)。我正在使用 Python 来做到这一点。

我关注了以下讨论:

get writing access to raw devices using python with windows

我遇到了同样的问题kcstrom有那个问题。我得到一个

    Traceback (most recent call last):
File "C:\script.py", line 49, in <module>
disk.write(data)
IOError: [Errno 9] Bad file descriptor

应有的读书求职,读到的资料是正确的。

目前我所知道的:

  1. 应在扇区大小的读/写/寻道中处理驱动器。
  2. 磁盘必须以'rb+'模式打开。
  3. 同时使用\\.\L: 和\\.\PhysicalDriveN 产生相同的结果。
  4. 脚本必须在管理员权限下运行。
  5. 卸载驱动器并尝试访问\\.\PhysicalDriveN 文件 - 即使以管理员身份运行时也“权限被拒绝”。

要重现错误:(警告:此代码可能会损坏物理驱动器,仅当您知道自己在做什么时才运行)

SOME_OFFSET = 123123
SOME_SIZE = 100
# replace L with the drive letter
disk = open('\\\\.\\L:','r+b')
# or use: (replace N with the drive number)
# disk = open('\\\\.\\PhysicalDriveN','r+b')
disk.seek(SOME_OFFSET*512)
data = disk.read(SOME_SIZE*512)
#modify data...
disk.seek(SOME_OFFSET*512)
disk.write(data)

我不知道这是权限问题还是我打开驱动器的方式有问题。

最佳答案

根据 MSDN 技术说明 "Blocking Direct Write Operations to Volumes and Disks" :

Write operations on a DASD volume handle will succeed if the file system is not mounted, or if:

  • The sectors being written to are the boot sectors.
  • The sectors being written to reside outside file system space.
  • The file system has been locked implicitly by requesting exclusive write access.
  • The file system has been locked explicitly by sending down a lock/dismount request.

....

Write operations on a disk handle will succeed if:

  • The sectors being written to do not fall within a file system.
  • The sectors being written to fall within a mounted file system that is locked explicitly.
  • The sectors being written to fall within a file system that is not mounted or the volume has no file system.

这是一个用于锁定卷的简单上下文管理器。它使用 win32file和来自 PyWin32 的 winoctlcon 模块。

import msvcrt
import win32file
import winioctlcon
import contextlib

@contextlib.contextmanager
def lock_volume(vol):
hVol = msvcrt.get_osfhandle(vol.fileno())
win32file.DeviceIoControl(hVol, winioctlcon.FSCTL_LOCK_VOLUME,
None, None)
try:
yield vol
finally:
try:
vol.flush()
finally:
win32file.DeviceIoControl(hVol, winioctlcon.FSCTL_UNLOCK_VOLUME,
None, None)

if __name__ == '__main__':
VOLUME_PATH = r'\\.\E:'
OFFSET = 123123
SIZE = 100

with open(VOLUME_PATH, 'r+b') as disk:
with lock_volume(disk):
disk.seek(OFFSET * 512)
data = disk.read(SIZE * 512)
disk.seek(OFFSET * 512)
disk.write(data)
input('press enter to unlock the volume')

关于python - 在 Windows 上将原始数据写入物理磁盘(闪存驱动器)失败并显示 "Bad file descriptor"- Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40239626/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com