【问题标题】:how to make a usb read-only with python?如何使用 python 将 USB 设为只读?
【发布时间】:2018-04-01 11:45:58
【问题描述】:

我正在尝试使用 pycharm 将 USB 设为只读。 我尝试使用我找到的代码,尽管它们在常规文件夹上工作,但它们不适用于 usb 目录。请帮帮我:)

import win32security
import ntsecuritycon as con
import getpass

file_name = r'F:\\' #THE USB


sd = win32security.GetFileSecurity(file_name, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl()


ace_count = dacl.GetAceCount()
print('Ace count:', ace_count)

for i in range(0, ace_count):
    dacl.DeleteAce(0)


userx, domain, type = win32security.LookupAccountName("", "my.user")


dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION, 3, 1179785, userx) # Read only


sd.SetSecurityDescriptorDacl(1, dacl, 0)   # may not be necessary
win32security.SetFileSecurity(file_name, win32security.DACL_SECURITY_INFORMATION, sd)

【问题讨论】:

  • 只有 NTFS 支持 ACL。 FAT 没有,通常用于 USB 便携式驱动器。

标签: python security pycharm usb readonly


【解决方案1】:

因此,在网上挖掘了更多内容并完全改变了我解决这个问题的方法之后,我终于能够让我的 USB 只读,反之亦然。希望您会发现我的解决方案很有用。 我找到了不同的来源,所以这并不是真正的“我的灵魂”,它的不同代码已根据我的需要进行了编辑和调整。

import _winreg
import usb

REG_PATH = r"SYSTEM\CurrentControlSet\Control\StorageDevicePolicies"

# Equivalent of the _IO('U', 20) constant in the linux kernel.
USBDEVFS_RESET = ord('U') << (4 * 2) | 20

def set_reg(name, value):
        try:
                _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, REG_PATH)
                print "1"
                registry_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, REG_PATH,0, _winreg.KEY_SET_VALUE)
                _winreg.SetValueEx(registry_key, name, 0, _winreg.REG_DWORD, value)
                _winreg.CloseKey(registry_key)
                return True
        except:
                "oops"


name = "WriteProtect"
value = 1 # 1 is read only 0 is also writable

x = set_reg(name,value) # make the usb read only or writable
print x


#reseting the usb device
my_device = usb.core.find()
my_device.reset() # reset the usb to apply the effect

几个重要说明:

1.这段代码可以分成两部分,第一部分使usb只读,反之亦然,第二部分从计算机内重新加载/重置usb。

2.您可能需要在注册表中创建“StorageDevicePolicies”键。

3.您可能需要安装 libusb-win32-devel-filter-1.2.6.0.exe 才能在 USB 设备上创建后端。

4.此方案使电脑上的所有usb设备只读(或可写)

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多