简体   繁体   中英

how to make a usb read-only with python?

I am trying to make a usb read-only using pycharm. I tried using codes that I found and although they worked on regular folders they didn't work with the usb directory. 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. 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.

2.you might need to create the "StorageDevicePolicies" key in the registry.

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.

4.this solution makes all the usb devices on the computer read only (or writable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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