[英]how to make a usb read-only with python?
I am trying to make a usb read-only using pycharm. 我正在尝试使用pycharm将USB设为只读。 I tried using codes that I found and although they worked on regular folders they didn't work with the usb directory.
我尝试使用找到的代码,尽管它们在常规文件夹上工作,但不适用于usb目录。 please help me :)
请帮我 :)
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)
So after digging more in the net and totally changing my approach to this problem I was able finally to make my usb read only and and vice versa. 因此,在深入研究网络并彻底改变我对这个问题的态度之后,我终于能够使我的USB变为只读,反之亦然。 hope you will find my solution useful.
希望您会发现我的解决方案有用。 I found different sources so this is not really "my soultion", its different codes edited and adjusted to my needs.
我找到了不同的来源,所以这并不是真正的“我的灵魂”,它的不同代码已编辑并根据我的需要进行了调整。
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
Few Important notes: 一些重要注意事项:
1.this code can be splitted into 2 parts , the first makes the usb read only or vice versa the second reloads/resets the usb from within the computer. 1.此代码可分为两部分,第一部分使USB成为只读,反之亦然,第二部分从计算机内部重新加载/重置USB。
2.you might need to create the "StorageDevicePolicies" key in the registry. 2.您可能需要在注册表中创建“ StorageDevicePolicies”项。
3.you might need to install libusb-win32-devel-filter-1.2.6.0.exe in orded to create the backend on the usb device. 3.您可能需要按顺序安装libusb-win32-devel-filter-1.2.6.0.exe才能在USB设备上创建后端。
4.this solution makes all the usb devices on the computer read only (or writable) 4.此解决方案使计算机上的所有USB设备均为只读(或可写)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.