如何在python中更改windows中的文件访问

2024-09-29 00:14:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序处理一个相关的文件,如果某些条件得到满足,那么它必须阻止对该文件的访问(读写),对所有用户,甚至对管理员。在

稍后,当调用另一个函数时,它必须将访问控制设置更改为正常。在

我试过以下代码

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)

阻止写访问很好。但我不能阻止读访问。我也不知道有什么方法可以恢复以前的访问设置,因为如果我阻止管理员的读访问,它将不会word。在

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


Tags: andtheimportforosshowfilenamecon