1

我的程序处理一个特定的文件,如果满足某些条件,那么它必须阻止所有用户甚至管理员对该文件的访问(READ n WRITE)。

稍后,当调用另一个函数时,它必须将访问控制设置恢复正​​常。

我试过下面的代码

import os, sys
import win32api
import win32security
import ntsecuritycon as con

FILENAME = "temp.txt"
os.remove (FILENAME)

def show_cacls (filename):
print
print
for line in os.popen ("cacls %s" % filename).read ().splitlines ():
print line

#
# Find the SIDs for Everyone, the Admin group and the current user
#
everyone, domain, type = win32security.LookupAccountName ("", "Everyone")
admins, domain, type = win32security.LookupAccountName ("", "Administrators")
user, domain, type = win32security.LookupAccountName ("", win32api.GetUserName ())

#
# Touch the file and use CACLS to show its default permissions
# (which will probably be: Admins->Full; Owner->Full; Everyone->Read)
#    
open (FILENAME, "w").close ()
show_cacls (FILENAME)

#
# Find the DACL part of the Security Descriptor for the file
#
sd = win32security.GetFileSecurity (FILENAME, win32security.DACL_SECURITY_INFORMATION)

#
# Create a blank DACL and add the three ACEs we want
# We will completely replace the original DACL with
# this. Obviously you might want to alter the original
# instead.
#
dacl = win32security.ACL ()
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_GENERIC_ALL, everyone)
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_GENERIC_ALL , user)
dacl.AddAccessAllowedAce (win32security.ACL_REVISION, con.FILE_GENERIC_ALL, admins)

#
# Put our new DACL into the Security Descriptor,
# update the file with the updated SD, and use
# CACLS to show what's what.
#
sd.SetSecurityDescriptorDacl (1, dacl, 0)
win32security.SetFileSecurity (FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)
show_cacls (FILENAME)

它可以很好地阻止写访问。但我不能阻止读取访问。另外我不知道有什么方法可以恢复以前的访问设置,因为如果我阻止 admin 的读取访问,它就不会说话。

请告诉我如何实现所需的功能。

4

0 回答 0