繁体   English   中英

如何使用python将USB设为只读?

[英]how to make a usb read-only with python?

我正在尝试使用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)

因此,在深入研究网络并彻底改变我对这个问题的态度之后,我终于能够使我的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设备均为只读(或可写)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM