簡體   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