2014-04-03 41 views
0
I have used the following to grant access to a file. Courtesy of kindall 

https://stackoverflow.com/a/12168268/740899在Windows上使用Python

> import win32security 
> import ntsecuritycon as con 
> 
> FILENAME = "whatever" 
> 
> userx, domain, type = win32security.LookupAccountName ("", "User X") 
> 
> sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION) 
> dacl = sd.GetSecurityDescriptorDacl() # instead of dacl = win32security.ACL() 
> 
> dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, userx) 
> 
> sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary 
> win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd) 

然而,訪問必須臨時刪除文件的權限。所以我用dacl.AddAccessDeniedAce代替上面顯示的dacl.AddAccessAllowedAce。但是,這會產生不良行爲,因爲我的用戶將來需要再次進行臨時訪問。在運行AddAccessDeniedAce,然後重新運行AddAccessAllowedAce後,被拒絕的控制仍然存在,並且我的用戶仍然無法訪問該文件。當用戶不再需要訪問時,我想完全刪除它們。這可以通過屬性菜單在Windows資源管理器來完成:

enter image description here

我一直沒能找到文件,以支持這樣的任務。有沒有人知道如何通過操縱DACL來做到這一點?或者我將不得不通過Windows界面手動執行此操作?

+0

我目前正在看[這篇文章](http://stackoverflow.com/a/18742636/740899),看看我能否這樣做。 – ionalchemist

+0

所以我已經確定每個這些方法都將單獨的ACE添加到文件中。我相信我可能需要刪除ACE。正在努力。 – ionalchemist

回答

0

在這裏找到一個解決方案:http://voices.canonical.com/tag/windows/

我不得不調整它一點,但它的工作。呼!

def remove_ace(path,usernames): 
    """Remove the ace for the given users.""" 
    if not os.path.exists(path): 
     raise WindowsError('Path %s could not be found.' % path) 
    total = 0 
    for x in usernames: 
     userx, domain, utype = win32security.LookupAccountName("", x) 
     sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION) 
     dacl = sd.GetSecurityDescriptorDacl() 
     num_delete = 0 
     for index in range(0, dacl.GetAceCount()): 
      ace = dacl.GetAce(index - num_delete) 
      if userx == ace[2]: 
       dacl.DeleteAce(index - num_delete) 
       num_delete += 1 
       total += 1 
     if num_delete > 0: 
      sd.SetSecurityDescriptorDacl(1, dacl, 0) 
      win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd) 
    if total > 0: 
     return True